正则表达式删除外部括号

时间:2012-05-26 12:53:30

标签: php regex preg-replace brackets

我一直在使用这个/\(\s*([^)]+?)\s*\)/正则表达式来删除PHP preg_replace函数的外括号(在我之前的问题Regex to match any character except trailing spaces中阅读更多内容)。

当只有一对括号时,这样可以正常工作,但问题是当有更多时,例如( test1 t3() test2)变为test1 t3( test2)而不是test1 t3() test2

我知道正则表达式的局限性,但是如果我只有一对括号可以让它不匹配,那就太好了。

因此,示例行为足够好:

( test1 test2 ) => test1 test2

( test1 t3() test2 ) => (test1 t3() test2)

修改

我想在删除的括号内修剪尾随空格。

3 个答案:

答案 0 :(得分:2)

您可以使用此基于递归正则表达式的代码,该代码也可以使用嵌套括号。唯一的条件是括号应该平衡。

$arr = array('Foo ( test1 test2 )', 'Bar ( test1 t3() test2 )', 'Baz ((("Fdsfds")))');
foreach($arr as $str)
   echo "'$str' => " . 
         preg_replace('/ \( \s* ( ( [^()]*? | (?R) )* ) \s* \) /x', '$1', $str) . "\n";

输出:

'Foo ( test1 test2 )' => 'Foo test1 test2'
'Bar ( test1 t3() test2 )' => 'Bar test1 t3() test2'
'Baz ((("Fdsfds")))' => 'Baz (("Fdsfds"))'

答案 1 :(得分:0)

试试这个

$result = preg_replace('/\(([^)(]+)\)/', '$1', $subject);

更新

\(([^\)\(]+)\)(?=[^\(]+\()

RegEx解释

"
\(            # Match the character “(” literally
(             # Match the regular expression below and capture its match into backreference number 1
   [^\)\(]       # Match a single character NOT present in the list below
                    # A ) character
                    # A ( character
      +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\)            # Match the character “)” literally
(?=           # Assert that the regex below can be matched, starting at this position (positive lookahead)
   [^\(]         # Match any character that is NOT a ( character
      +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \(            # Match the character “(” literally
)
"

答案 2 :(得分:0)

你可能想要这个(因为我猜它是你最初想要的):

$result = preg_replace('/\(\s*(.+)\s*\)/', '$1', $subject);

这将得到

"(test1 test2)" => "test1 test2"
"(test1 t3() test2)" => "test1 t3() test2"
"( test1 t3(t4) test2)" => "test1 t3(t4) test2"