views:

590

answers:

3

Hi, I'm just wondering how I could remove the text between a set of parentheses and the parentheses themselves in php.

Example :

ABC (Test1)

I would like it to delete (Test1) and only leave ABC

Thanks

+1  A: 
$string = "ABC (Test1)";
echo preg_replace("/\([^\)]+\)/","",$string); // 'ABC '

preg_replace is a perl-based regular expression replace routine. What this script does is matches all occurrences of a opening parenthesis, followed by any number of characters not a closing parenthesis, and again followed by a closing parenthesis, and then deletes them:

Regular expression breakdown:

/  - opening delimiter (necessary for regular expressions, can be any character that doesn't appear in the regular expression
\( - Match an opening parenthesis
[^\)]+ - Match 1 or more character that is not a closing parenthesis
\) - Match a closing parenthesis
/  - Closing delimiter
cmptrgeekken
wow :O Fast reply! Thanks! Would you mind explaining it a little though? I don't really get what you've done.
Belgin Fish
You shouldn't try and escape the ) in your character class.
mopoke
It's a regular expression. It's kinda hard to explain hehe.
metrobalderas
Explained slightly. Hope it makes sense.
cmptrgeekken
A: 

without regex

$string="ABC (test)"
$s=explode("(",$string);
print trim($s[0]);
ghostdog74
A: 

Folks, regular expressions CANNOT be used to parse non-regular languages. Non-regular languages are those that require state (i.e. remembering how many parenthesis are currently open).

All of the above answers will fail on this string: "ABC (hello (world) how are you)".

Read Jeff Atwood's Parsing Html The Cthulhu Way: http://www.codinghorror.com/blog/archives/001311.html, and then use either a by-hand written parser (loop through the characters in the string, see if the character is a parenthesis or not, maintain a stack) or use a lexer/parser.

Alex