4

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

当只有一对括号时,这很好用,但问题是当有更多时,例如( test1 t3() test2)变成test1 t3( test2)instead test1 t3() test2

我知道正则表达式的限制,但如果我可以让它不匹配任何东西,如果有一对以上的括号,那就太好了。

因此,示例行为就足够了:

( test1 test2 )=>test1 test2

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

编辑:

我想继续修剪已删除括号内的尾随空格。

4

3 回答 3

3

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

$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"))'
于 2012-05-26T14:32:07.340 回答
0

试试这个

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

更新

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

正则表达式解释

"
\(            # 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
)
"
于 2012-05-26T12:57:11.940 回答
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"
于 2012-05-26T13:06:52.157 回答