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

76

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.

764

Answer

Solution:

This will replaceschool of ... withschool of [X] and... school with[X] shool unless followed byof

$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";

Output:

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

Answer

Solution:

You may use this lookaround based regex for search:

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

Replace it by:

[X]

RegEx Demo

PHP Code:

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

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

People are also looking for solutions to the problem: cant make JSON multi level PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.