Arun Arun - 1 year ago 100
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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download