Getting contents of square brackets, avoiding nested brackets

℡╲_俬逩灬. 提交于 2019-12-10 18:44:59

问题


(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]'; 

回答1:


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



回答2:


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]);


来源:https://stackoverflow.com/questions/2110617/getting-contents-of-square-brackets-avoiding-nested-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!