Forum Moderators: coopster

Message Too Old, No Replies

preg match recursion nested parentheses

getting content inside square brackets

         

topwebdesigns

3:44 pm on Jan 21, 2010 (gmt 0)

10+ Year Member



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))*\)/';
$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]';

topwebdesigns

4:37 pm on Jan 21, 2010 (gmt 0)

10+ Year Member



Sorry, I posted the wrong regex in that example, it's supposed to be:

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