stunnaman
stunnaman

Reputation: 911

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.

Upvotes: 12

Views: 35777

Answers (3)

James Wheare
James Wheare

Reputation: 4810

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.

Upvotes: 49

Gumbo
Gumbo

Reputation: 655775

Try this:

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

Upvotes: 5

Alix Axel
Alix Axel

Reputation: 154671

$string = preg_replace('~\(.*?\)~', '', $string);

Upvotes: 1

Related Questions