是否可以在 php 中使用正则表达式替换短语前的单词?
Is it possible to replace a word before a phrase using regular expression in php?
输入文字: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);
感谢您的任何建议。
在正则表达式中使用 /\w+(?= school)/i
模式 select school
之前的任何单词。
$inputext = "Engineering school, Medical school";
$rule ="/\w+(?= school)/i";
$replacetext = "Educational";
$outputext = preg_replace($rule, $replacetext, $inputext);
检查结果 demo
您还可以使用 /\w+(?= school(,|$))/i
来防止匹配不想要的词,例如 @WiktorStribiżew 所说的 schoolboy
。
输入文字: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);
感谢您的任何建议。
在正则表达式中使用 /\w+(?= school)/i
模式 select school
之前的任何单词。
$inputext = "Engineering school, Medical school";
$rule ="/\w+(?= school)/i";
$replacetext = "Educational";
$outputext = preg_replace($rule, $replacetext, $inputext);
检查结果 demo
您还可以使用 /\w+(?= school(,|$))/i
来防止匹配不想要的词,例如 @WiktorStribiżew 所说的 schoolboy
。