Reza Alizade
Reza Alizade

Reputation: 328

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

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.

Upvotes: 1

Views: 55

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

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.

Upvotes: 1

Related Questions