Home > Net >  Regex to match a result that isn't single line and expanded across multiple lines
Regex to match a result that isn't single line and expanded across multiple lines

Time:03-31

I want to change /<\?php\s([\s\S]*?)\?>/gi the way that single line PHP tags become excluded.

For example, here I want to match only second PHP tag and not the first one:

Test number <?PHP echo($a);?> is here.

This is test number <?PHP echo($b);
$b = $a?> that expanded across multiple lines.

CodePudding user response:

You can use

<\?php(?!\S)((?:(?!<\?php(?!\S)|\?>).)*\R[\s\S]*?)\?>

A variation with multiline .:

<\?php\s((?:(?!<\?php\s|\?>).)*\R(?s:.*?))\?>

See the regex demo. Details:

  • <\?php - a <?php substring
  • (?!\S) - a right-hand whitespace boundary (immediately to the right, there must be either a whitespace or start of string)
  • ((?:(?!<\?php(?!\S)|\?>).)*\R[\s\S]*?) - Group 1:
    • (?:(?!<\?php(?!\S)|\?>).)* - any single char other than a line break char, zero or more and as many as possible occurrences, that does not start a <?php a right-hand whitespace boundary or ?>` char sequence
    • \R - a line break sequence
    • [\s\S]*? / (?s:.*?) - any zero or more chars as few as possible
  • \?> - a ?> substring.
  • Related