Regex to Grab Content of Recursive Parentheses

✔ Recommended Answer

For the given example, you could use a recursive pattern to match balanced parenthesis right after the @if.

Note that you are matching php code with a regex that may give unexpected side effects.

@if\h*(\(((?:[^()]++|(?1))*)\))\s*(.*?)\s*@endif\b
  • @if\h* Match @if followed by optional spaces
  • ( Capture group 1
    • \( Match (
    • ( Capture group 2
      • (?:[^()]++|(?1))* Repeat matching any char except ( or ) or repeat the first sub pattern
    • ) Close group 2
    • \) Match )
  • ) Close group 1
  • \s*(.*?)\s* Capture group 3, match any character as few as possible between optional whitespace chars
  • @endif\b Match @endif followed by a word boundary

Regex demo | Php demo

$pattern = '/@if\h*(\(((?:[^()]++|(?1))*)\))\s*(.*?)\s*@endif\b/is';$s = '@if(!empty($title)). testand testing   @endif';$subst = "<?php if($2) { ?>$3<?php } ?>";$result = preg_replace($pattern, $subst, $s);echo $result;

Output

<?php if(!empty($title)) { ?>. testand testing<?php } ?>

If you don't want to cross another @if( in between:

@if\h*(\(((?:[^()]++|(?1))*)\))\s*((?:(?!@if\h*\().)*)\s*@endif\b

Regex demo

Method #2

To grab the content of recursive parentheses in PHP using regular expressions, you can use the following regular expression pattern:

scss
/\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\)/

This regular expression pattern matches any text enclosed in parentheses, including nested parentheses.

Here's a breakdown of the pattern:

  • \( : matches an opening parenthesis
  • (?: : starts a non-capturing group
  • [^()]+ : matches one or more characters that are not parentheses
  • | : OR
  • \((?:[^()]+| : matches a nested opening parenthesis, followed by another non-capturing group
  • \([^()]*\) : matches any text enclosed in parentheses that may or may not have nested parentheses
  • )* : ends the nested non-capturing group and specifies that it can be repeated zero or more times
  • )* : ends the non-capturing group and specifies that it can be repeated zero or more times
  • \) `: matches a closing parenthesis

Here's an example of how to use this regular expression pattern in PHP:

php
$text = "This (is (a (nested) example) of) recursive parentheses."; preg_match_all("/\((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*\)/", $text, $matches); print_r($matches[0]);

This will output:

css
Array ( [0] => (nested) [1] => (a (nested) example) [2] => (is (a (nested) example) of) )

This shows that the regular expression pattern was able to match all the text enclosed in parentheses, including the nested parentheses.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755