Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Preg replace parentheses?

What is the proper syntax to preg_replace just the parenthesis in PHP?

$search = preg_replace('/\(\)/','',$search);

Thank you

like image 451
Norse Avatar asked Mar 01 '12 01:03

Norse


3 Answers

Assuming you want to remove both ( and ) from the $search string:

$search = preg_replace('/\(|\)/','',$search);

I think the fastest way to do this is using the strtr function, like this:

$search = strtr($search, array('(' => '', ')' => ''));
like image 57
J. Bruni Avatar answered Nov 07 '22 00:11

J. Bruni


That is the proper syntax, though preg_replace is for regular expressions, if you just want to replace () then str_replace is a couple of times faster.

If you want to replace ( or ) wherever they are, you could use

preg_replace("/\(|\)/", "", $str);
like image 20
Tony Bogdanov Avatar answered Nov 07 '22 01:11

Tony Bogdanov


You mean like this?

$search = preg_replace('/[()]/', '', $search);

This will strip all parenthesis without regard to pairing.

like image 2
Nilpo Avatar answered Nov 07 '22 01:11

Nilpo