tags:

views:

1244

answers:

3

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

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

Thanks for any answers!

A: 
$string = preg_replace('~\(.*?\)~', '', $string);
Alix Axel
+1  A: 

Try this:

preg_replace('/\([^)]*\)|[()]/', '', $str)
Gumbo
+2  A: 

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.

James Wheare
Well, you will want to leave one space to separate the two words.
Chacha102
Yep, that pattern only strips whitespace before the bracketed section, leaving whitespace after it. The other solutions would leave two spaces between words for the example in the question.
James Wheare
Note that this will break for "(())" or any unbalanced parentheses, but that may not be a problem.
Mark