是否可以使用 php 中的正则表达式根据条件替换词组(之前或之后)?

Is it possible to replace a word (before or after) a phrase based on condition using regular expression in php?

输入文字:Engineering School, Medical school, The School of Science, High School of science

需要输出:[X] school, [X] school, The School of [X], High School of [X]

规则:短语 school of 或(不区分大小写)或学校(不区分大小写)之前的任何单词都需要替换为 [X]。但是这两条规则不应该同时执行。

$inputext = "Engineering School, Medical school, The School of Science"; 
$rule ="/\w+(?= school)/i";
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

说清楚 - 应根据 'School of' 和 'School' 的出现触发规则(均不区分大小写)。 - 当出现 'School of' 时,不应触发 'School' 上的规则

感谢您的任何建议。

您可以使用这个基于环视的正则表达式进行搜索:

.*\K(?>(?<=school of )\w+|\b\w++(?= school))

替换为:

[X]

RegEx Demo

PHP代码:

$re = '/.*\K(?>(?<=school of )\w+|\b\w++(?= school))/';
$repl = preg_replace($re, '[X]', $str);

正则表达式详细信息:

  • .*\K: 匹配开头0个或多个字符并重置匹配信息
  • (?>:开始原子组
    • (?<=school of )\w+:匹配前面有"school of "
    • 的完整单词
    • |: 或
    • \b\w++(?= school):匹配一个完整的单词后跟" school"
  • ): 结束原子团

这会将 school of ... 替换为 school of [X],将 ... school 替换为 [X] shool,除非后跟 of

$inputext = "Queen's School, Engineering School, Medical school, The School of Science, High School of science the school is closed"; 
$rule = "/\b(?!the school is)(?:(?<=\bschool of )\S+|\S+(?= school\b(?! of)))/i";

$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext,"\n";

输出:

[X] School, [X] School, [X] school, The School of [X] High School of [X] the school is closed