regex - Is it possible to replace a word (before or after) a phrase based on condition using regular expression in php?
Input text:Engineering School, Medical school, The School of Science, High School of science
Output required:[X] school, [X] school, The School of [X], High School of [X]
Rule: any words before the phraseschool of
or (case insensitive) or School (case insensitive) needs to be replaced by[X]
. But both rule should not execute at the same time.
$inputext = "Engineering School, Medical school, The School of Science";
$rule ="/\w+(?= school)/i";
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);
To make it clear - the rule should be triggered based on occurrence of 'School of' and 'School' (both case insensitive). - When 'School of' is present then the rule on 'School' should not be triggered
Thanks for any suggestions.
Answer
Solution:
This will replace
school of ...
withschool of [X]
and... school
with[X] shool
unless followed byof
Output:
Answer
Solution:
You may use this lookaround based regex for search:
Replace it by:
RegEx Demo
PHP Code:
RegEx Details:
.*\K
: Match 0 or more characters at the start and reset the match info(?>
: Start atomic group(?<=school of )\w+
: Match a full word preceded by"school of "
: OR
|\b\w++(?= school)
: Match a full word followed by" school"
)
: End atomic group