php: remove brackets/contents from a string?


If I have a string like this:

$str = "blah blah blah (a) (b) blah blah blah";

How can I regex so that the output is:

$str = "blah blah blah blah blah blah";

It needs to be able to support any number of bracket pairs inside a string.

12/4/2017 8:03:21 PM

Accepted Answer

This should do the trick:

$str = trim(preg_replace('/\s*\([^)]*\)/', '', $str));

Note, this answer removes whitespace around the bracket too, unlike the other suggestions.

The trim is in case the string starts with a bracketed section, in which case the whitespace following it isn't removed.

8/26/2009 8:29:49 PM

Try this:

preg_replace('/\([^)]*\)|[()]/', '', $str)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow