Is it possible to replace a word after a phrase us

2019-03-06 18:18发布

问题:

Input text: school of engineering, school of medicine

Output required: school of education, school of education

Rule: any words followed by 'school of' needs to be replaced by 'education'

$inputext = "school of engineering, school of medicine"; 
$rule ="//s/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

Thanks for any suggestions.

回答1:

No need to capture anything or use lookarounds.

Demo: https://3v4l.org/uWZgW

$inputext = "school of engineering, school of medicine"; 
$rule ="/school of \K[a-z]+/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext;

Match the preceding words (and space after of), restart the fullstring match with \K, then replace the target word.



回答2:

Sure thing, just use a positive lookbehind on school of plus the space:
(?<=school of )\w+

  • (?<=school of ) matches anything that comes after school of and a space.
  • \w denotes any word character, and + denotes between one and an unlimited number.

So your code would be:

$inputext = "school of engineering, school of medicine"; 
$rule ="/(?<=school of )\w+/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

Which outputs:

school of education, school of education

This can be seen working on Regex101 here and 3val here.