Removing nested parentheses using regex in PHP

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

I have a line like this:

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

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

Therefore, I expect the result to be "Hustlin' " . "Hustlin' "

I tried the following:

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

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

Can someone explain what happened here?

+4
source share
3 answers

Your template \(.*?\) Matches a ( and then finds the first one ) (and everything in between): how did the template “understand” to fit the balanced bracket?

However, you can use a recursive PHP template:

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

will print:

  Hustlin 'with speed! 

Short break 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 ')' 
+8
source

Make a simple loop with replacing the regex inside.

Replace only first occurrence

 /\([^()]*\)/ 

with an empty string and repeat this until a match is found.

0
source

To answer your question: your regex statement with preg_replace matches and removes the first occurrence of the paranthesis sequence and everything inside it - regardless of whether another opening bracket appears.

0
source

Source: https://habr.com/ru/post/1438188/


All Articles