获取方括号的内容,避免嵌套括号

发布于 2024-08-19 02:35:41 字数 638 浏览 12 评论 0原文

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

我试图提取一些方括号的内容,但是我有一点麻烦。我已经让它适用于圆括号,如下所示,但我看不出应该如何修改它以适用于方括号。我本以为在这个例子中用圆形替换方形,反之亦然应该可行,但显然不行。

它需要忽略括号内的括号。所以它不会返回 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏雨凉 2024-08-26 02:35:41
$preg = '#\[((?>[^\[\]]+)|(?R))*\]#x';
$preg = '#\[((?>[^\[\]]+)|(?R))*\]#x';
蓝颜夕 2024-08-26 02:35:41

试试这个:

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

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]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文