我的PHP脚本调用Freebase API并输出一个字符串,该字符串可以包含任意数量的open和closed括号。每组打开然后关闭的括号本身也可以包含任意数量的打开然后关闭的括号。例如;
$string = "random string blah (a) (b) blah blah (brackets (within) brackets) blah";
如何使用PHP和正则表达式来操作字符串,从而导致输出不包含任何括号或括号本身的内容?例如;
$string = "random string blah blah blah blah";
答案 0 :(得分:9)
您可以使用递归正则表达式:
$result = preg_replace('/\(([^()]*+|(?R))*\)\s*/', '', $subject);
<强>说明:强>
\( # Match (
( # Match the following group:
[^()]*+ # Either any number of non-parentheses (possessive match)
| # or
(?R) # a (recursive) match of the current regex
)* # Repeat as needed
\) # Match )
\s* # Match optional trailing whitespace