在PHP中使用正则表达式删除嵌套括号

时间:2012-10-06 18:49:16

标签: php regex

  

可能重复:
  Can regular expressions be used to match nested patterns?

我有一个这样的字符串:

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

我想基本上删除括号中的所有内容。在上面使用嵌套括号的情况下,我想在顶层删除它。

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

我尝试了以下内容:

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

返回奇怪的结果:"Hustlin' Album Version )"

有人能解释一下这里发生了什么吗?

3 个答案:

答案 0 :(得分:8)

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

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

$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 ')'

答案 1 :(得分:0)

在里面用正则表达式替换做一个简单的循环。

仅替换第一次出现的

/\([^()]*\)/

使用空字符串并重复,直到找不到匹配项。

答案 2 :(得分:0)

回答你的问题:使用preg_replace 的正则表达式语句匹配并删除了第一次出现的paranthesis序列及其内部的所有内容 - 无论是否发生另一个开括号。