Skip to content
Advertisement

Regex to match a result that isn’t single line and expanded across multiple lines

I want to change /<?phps([sS]*?)?>/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.

Advertisement

Answer

You can use

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

A variation with multiline .:

<?phps((?:(?!<?phps|?>).)*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[sS]*?) – 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
    • [sS]*? / (?s:.*?) – any zero or more chars as few as possible
  • ?> – a ?> substring.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement