Is it possible to replace a word after a phrase using regular expression in php?

前端 未结 2 1689
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 10:30

Input text: school of engineering, school of medicine

Output required: school of education, school of education

Rule: any words followed by \'school of\' needs t

2条回答
  •  生来不讨喜
    2021-01-29 11:19

    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.

提交回复
热议问题