获取方括号的内容,避免嵌套括号
(第一次发帖,通过谷歌的长期访问者)
我试图提取一些方括号的内容,但是我有一点麻烦。我已经让它适用于圆括号,如下所示,但我看不出应该如何修改它以适用于方括号。我本以为在这个例子中用圆形替换方形,反之亦然应该可行,但显然不行。
它需要忽略括号内的括号。所以它不会返回 (11) 而是会返回 (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)
)
这是完美的。但是,我怎样才能让它适用于带有方括号的字符串,例如:
$str = '123[456][789][10[11]12]';
(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]';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this: