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

时间:2018-10-03 09:53:20

标签: php regex preg-replace

输入文字: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或(不区分大小写)或School(不区分大小写)短语之前的任何单词都需要替换为[X]。但是,这两个规则不应同时执行。

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

说明清楚  -应该基于“学校”和“学校”(都不区分大小写)的出现来触发规则。  -如果存在“学校”,则不应触发“学校”规则

谢谢您的建议。

2 个答案:

答案 0 :(得分:1)

这将用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

答案 1 :(得分:0)

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

.*\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);

RegEx详细信息:

  • .*\K:首先匹配0个或更多字符,然后重置匹配信息
  • (?>:开始原子组
    • (?<=school of )\w+:匹配以"school of "结尾的完整单词
    • |:或
    • \b\w++(?= school):匹配完整的单词,后跟" school"
  • ):终止原子团