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";
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
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