开发者

Getting contents of square brackets, avoiding nested brackets

开发者 https://www.devze.com 2022-12-16 22:52 出处:网络
(first time poster, long time visitor via Google) I\'m trying to extract the contents of some square brackets, however i开发者_JS百科\'m having a spot of bother. I\'ve got it working for round bracke

(first time poster, long time visitor via Google)

I'm trying to extract the contents of some square brackets, however i开发者_JS百科'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]'; 


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


Try this:

$str = '123[456][789][10[11]12]';
$pattern = '/(([\d]+)|(\[[\d]+\])|\[[\d\[\]]+\])/';
preg_match_all($pattern,$str,$matches);
print_r($matches[0]);
//or
$str = '123[456][789][10[11]12]';
$pattern = '/(([\d]+)|(\[[\d]+\]))/';
preg_match_all($pattern,$str,$matches);
print_r($matches[0]);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号