Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing nested parentheses using regex in PHP [duplicate]

Tags:

regex

php

Possible Duplicate:
Can regular expressions be used to match nested patterns?

I have a string like this:

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

and I want to basically remove everything in parentheses. In the case above with nested parentheses, I want to just remove it at the top level.

So I expect the result to just be "Hustlin' ".

I tried the following:

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

which returns the odd result of: "Hustlin' Album Version )".

Can someone explain what happened here?

like image 928
Andy Hin Avatar asked Dec 27 '22 16:12

Andy Hin


1 Answers

Your pattern \(.*?\) matches a ( and will then find the first ) (and everything in between): how would the pattern "understand" to match balanced parenthesis?

However, you could make use of PHP's recursive pattern:

$string = "Hustlin' ((Remix) Album Version (Explicit)) with (a(bbb(ccc)b)a) speed!";
echo preg_replace("/\(([^()]|(?R))*\)/", "", $string) . "\n";

would print:

Hustlin'  with  speed!

A short break down of the pattern:

\(         # 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 ')'
like image 193
Bart Kiers Avatar answered Dec 29 '22 05:12

Bart Kiers