Mustafa Mustafa - 1 month ago 6
PHP Question

PHP regex help. preg_replace

I have four words

A,B,C,D
.
I want to replace all occurrences of
A B
or
A C
with
A D
in given sentence.

I have written this
preg_replace("/([A])\s[C|B]/i", "\1 D",$sentence);


But it is not giving correct output. Where I am going wrong?

Answer

\ within " are escaping the string special characters, not the regexp special characters. Either you ' as string delimiter or double \ characters:

preg_replace('/([A])\s[C|B]/i', '\1 D', $sentence);