Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strip all brackets from string [duplicate]

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

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

How can I use PHP and regex to manipulate the string resulting in an output that doesn't contain the contents of any brackets or the brackets themselves? For example;

$string = "random string blah blah blah blah";
like image 273
Callum Whyte Avatar asked Jan 12 '23 16:01

Callum Whyte


1 Answers

You can use a recursive regex:

$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
like image 69
Tim Pietzcker Avatar answered Jan 22 '23 14:01

Tim Pietzcker