获取方括号的内容,避免嵌套括号 [英] Getting contents of square brackets, avoiding nested brackets

查看:67
本文介绍了获取方括号的内容,避免嵌套括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(第一次发帖,谷歌长期访问者)

(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.

它需要忽略括号内的括号.所以它不会返回 (11) 而是返回 (10(11)12).

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

这篇关于获取方括号的内容,避免嵌套括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆