Arun Arun - 1 month ago 5x
PHP Question

Extract string not between parentheses

I have a string like

"which I want (which I don't want)"
, here using php I want to extract only
"which I want"

So I want to exclude the string enclosed in parenthesis
(which I do not want)
in my result string.

I tried this but it doesn't work:

$val = "which I want (which I don't want)";
reg_replace('/((.*))/', '', $val);


You almost had it. Since the parenthesis are special characters in regular expressions, you have to escape them in order for it to work:

preg_replace('/(\s?\(.*\))/', '', $val);

( and ) are group delimiters in RegEx, whereas \( and \) are literal parenthesis.

I also added an optional whitespace before the parenthesis so you get rid of that too.