在PHP中使用正则表达式删除嵌套括号 [英] Removing nested parentheses using regex in PHP

查看:275
本文介绍了在PHP中使用正则表达式删除嵌套括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
可以使用正则表达式来匹配嵌套模式吗?

Possible Duplicate:
Can regular expressions be used to match nested patterns?

我有一个像这样的字符串:

I have a string like this:

$string = "Hustlin' ((Remix) Album Version (Explicit))";

,我想基本上删除括号中的所有内容.在上面带有嵌套括号的情况下,我只想在顶层将其删除.

and I want to basically remove everything in parentheses. In the case above with nested parentheses, I want to just remove it at the top level.

所以我希望结果只是"Hustlin' ".

我尝试了以下操作:

preg_replace("/\(.*?\)/", '', $string);|

返回奇数结果:"Hustlin' Album Version )".

有人可以解释这里发生了什么吗?

Can someone explain what happened here?

推荐答案

您的模式\(.*?\)(匹配,然后将找到第一个)(以及介于两者之间的所有内容):模式如何理解"匹配平衡括号?

Your pattern \(.*?\) matches a ( and will then find the first ) (and everything in between): how would the pattern "understand" to match balanced parenthesis?

但是,您可以利用PHP的递归模式:

However, you could make use of PHP's recursive pattern:

$string = "Hustlin' ((Remix) Album Version (Explicit)) with (a(bbb(ccc)b)a) speed!";
echo preg_replace("/\(([^()]|(?R))*\)/", "", $string) . "\n";

将打印:

Hustlin'  with  speed!

模式的简短细分:

\(         # match a '('
(          # start match group 1
  [^()]    #   any char except '(' and ')'
  |        #   OR
  (?R)     #   match the entire pattern recursively
)*         # end match group 1 and repeat it zero or more times
\)         # match a ')'

这篇关于在PHP中使用正则表达式删除嵌套括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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