首页 > 解决方案 > 是否可以在 php 中使用正则表达式替换短语后的单词?

问题描述

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

所需输出:教育学校,教育学校

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

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

感谢您的任何建议。

标签: phpregexpreg-replace

解决方案


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

演示: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,然后替换目标单词。


推荐阅读