是否可以在php中使用正则表达式替换词组之前的单词?

时间:2018-10-03 09:22:37

标签: php regex string preg-replace

输入文字:Engineering School, Medical school

要求的输出:Educational school, Educational school

规则:school短语(不区分大小写)之前的任何单词都需要替换为Educational

$inputext = "Engineering School, Medical school"; 
$rule ="//s/";
$replacetext = "Educational";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

谢谢您的建议。

1 个答案:

答案 0 :(得分:1)

在正则表达式中使用/\w+(?= school)/i模式来选择school之前的任何单词。

$inputext = "Engineering school, Medical school"; 
$rule ="/\w+(?= school)/i";
$replacetext = "Educational";
$outputext = preg_replace($rule, $replacetext, $inputext);

demo中查看结果

另外,您可以使用/\w+(?= school(,|$))/i来防止匹配schoolboy之类的不想要的单词,如@WiktorStribiżew所说。