1

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.

1 Answers1

1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks I used first code, BTW I replaced `\R` with `\n` to work. Also it doesn't match if we have ` – Reza Nooralizadeh Mar 30 '22 at 15:11
  • @RezaNooralizadeh `\n` is not enough if you have CRLF line endings. The regex [works fine](https://regex101.com/r/gj0C9b/3) if ` – Wiktor Stribiżew Mar 30 '22 at 17:14
  • In your example, second PHP section has 3 lines but if you remove middle line, it doesn't get matched. BTW I use this regex in addition to the other one: `<\?php\n[\s\S]*?\?>` – Reza Nooralizadeh Mar 31 '22 at 00:56
  • @RezaNooralizadeh Ok, `\s` consumed the newline here and `\R` could not find any match. It is then better to use either a whitespace boundary - `<\?php(?!\s)((?:(?!<\?php\b|\?>).)*\R[\s\S]*?)\?>` - or a word boundary, `<\?php\b((?:(?!<\?php\b|\?>).)*\R[\s\S]*?)\?>`. – Wiktor Stribiżew Mar 31 '22 at 07:32
  • 1
    Thanks. Now first code in the edited answer works fine – Reza Nooralizadeh Mar 31 '22 at 12:01