Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Text Between Parentheses PHP

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

like image 379
Belgin Fish Avatar asked Feb 01 '10 02:02

Belgin Fish


3 Answers

$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
like image 75
cmptrgeekken Avatar answered Sep 20 '22 03:09

cmptrgeekken


The accepted answer works great for non-nested parentheses. A slight modification to the regex allows it to work on nested parentheses.

$string = "ABC (Test1(even deeper) yes (this (works) too)) outside (((ins)id)e)";
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $string);
like image 22
Tegan Snyder Avatar answered Sep 23 '22 03:09

Tegan Snyder


without regex

$string="ABC (test)"
$s=explode("(",$string);
print trim($s[0]);
like image 13
ghostdog74 Avatar answered Sep 22 '22 03:09

ghostdog74