Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: remove brackets/contents from a string?

Tags:

regex

php

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.

like image 959
stunnaman Avatar asked Aug 26 '09 18:08

stunnaman


2 Answers

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.

like image 155
James Wheare Avatar answered Oct 06 '22 00:10

James Wheare


Try this:

preg_replace('/\([^)]*\)|[()]/', '', $str)
like image 35
Gumbo Avatar answered Oct 05 '22 22:10

Gumbo