rasputin rasputin - 7 months ago 8
PHP Question

How can I do a regex match string in a string which contains some characters or not?

Let's say I have the following string and want to strip out "two three" whether it is in parenthesis or not.

one two three four
one (two three) four
one ( two three ) four
one (two three four
one two three) four
one ( two three four
one two three ) four


I want to strip these to

one four


I tried that but no luck.

$str = preg_replace('/(\(| )two(.*?)three( |\))\S+ */i', '', $str);

Answer

You can use this regex :

(\(? ?two three ?\)?)

demo