在 php 中是否可以使用正则表达式替换短语后的单词?

Is it possible to replace a word after a phrase using regular expression in php?

输入文字:工学院、医学院

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

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

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

感谢您的任何建议。

没问题,只需在 school of 上使用 positive lookbehind 加上 space:
(?<=school of )\w+

  • (?<=school of ) 匹配 school of 和 space.
  • 之后的任何内容
  • \w表示任意单词字符,+表示一个到无限个数之间。

因此您的代码将是:

$inputext = "school of engineering, school of medicine"; 
$rule ="/(?<=school of )\w+/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

输出:

school of education, school of education

这可以在 Regex101 上看到 here and 3val here.

无需捕获任何内容或使用环顾四周。

演示: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之后的space),用\K重新开始全字符串匹配,然后替换目标词。