Search code examples
phpregexrecursionpreg-matchparentheses

Getting contents of square brackets, avoiding nested brackets


(first time poster, long time visitor via Google)

I'm trying to extract the contents of some square brackets, however i'm having a spot of bother. I've got it working for round brackets as seen below, but I can't see how it should be modified to work for square brackets. I would have thought replacing the round for square and vice versa in this example should work, but apparently not.

It needs to ignore brackets within brackets. So it won't return (11) but will return (10(11)12).

$preg = '#\(((?>[^()]+)|(?R))*\)#x';
$str = '123(456)(789)(10(11)12)';

if(preg_match_all($preg, $str, $matches)) {
    $matches = $matches[0];
} else {
    $matches = array();
}

echo '<pre>'.print_r($matches,true).'</pre>';

This returns:

Array (
    [0] => (456)
    [1] => (789)
    [2] => (10(11)12)
)

Which is perfect. However, how can I get this working for a string with square brackets instead e.g:

$str = '123[456][789][10[11]12]'; 

Solution

  • $preg = '#\[((?>[^\[\]]+)|(?R))*\]#x';