Regex to remove outer brackets

杀马特。学长 韩版系。学妹 提交于 2019-12-04 10:17:17

You can use this recursive regex based code that will work with nested brackets also. Only condition is that brackets should be balanced.

$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";

OUTPUT:

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

Try this

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

Update

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

RegEx explanation

"
\(            # 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
)
"

You may want this (As I guess it is what you want originally):

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

This would get

"(test1 test2)" => "test1 test2"
"(test1 t3() test2)" => "test1 t3() test2"
"( test1 t3(t4) test2)" => "test1 t3(t4) test2"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!