Search code examples
phpreplacepreg-replacequotingbackreference

Backreference \1 in replacement string of preg_replace() is not substituting the captured text from the regex pattern


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?

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

The \1 is not using the captured A in the result text.


Solution

  • \ 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);