PHP removes all brackets from a string

My PHP script calls the Freebase API and outputs a string that can contain any number of open closed brackets. Each set of open closed brackets can also contain any number of open and then closed brackets. For instance:

$string = "random string blah (a) (b) blah blah (brackets (within) brackets) blah"; 

How can I use PHP and regex to control a string that results in output that does not contain the contents of any brackets or parentheses? For instance:

 $string = "random string blah blah blah blah"; 
+4
source share
1 answer

You can use a recursive regular expression:

 $result = preg_replace('/\(([^()]*+|(?R))*\)\s*/', '', $subject); 

Explanation:

 \( # Match ( ( # Match the following group: [^()]*+ # Either any number of non-parentheses (possessive match) | # or (?R) # a (recursive) match of the current regex )* # Repeat as needed \) # Match ) \s* # Match optional trailing whitespace 
+9
source

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


All Articles