是否可以在php中使用正则表达式替换短语后的单词? [英] Is it possible to replace a word after a phrase using regular expression in php?

查看:21
本文介绍了是否可以在php中使用正则表达式替换短语后的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入文本:工程学院、医学院

Input text: school of engineering, school of medicine

输出要求:教育学院,教育学院

Output required: school of education, school of education

规则:任何跟在school of"后面的词都需要用education"代替

Rule: any words followed by 'school of' needs to be replaced by 'education'

$inputext = "school of engineering, school of medicine"; 
$rule ="//s/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

感谢您的任何建议.

推荐答案

无需捕获任何内容或使用环视.

No need to capture anything or use lookarounds.

演示:https://3v4l.org/uWZgW

$inputext = "school of engineering, school of medicine"; 
$rule ="/school of \K[a-z]+/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext;

匹配前面的单词(以及of之后的空格),用\K重新开始全串匹配,然后替换目标单词.

Match the preceding words (and space after of), restart the fullstring match with \K, then replace the target word.

这篇关于是否可以在php中使用正则表达式替换短语后的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆