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?
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 ')'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With