The escape sequence \g used as a backreference may not always behave as expected.The following numbered backreferences refer to the text matching the specified capture group, as documented:\1\g1\g{1}\g-1\g{-1}However, the following variants refer to the subpattern code instead of the matched text:\g<1>\g'1'\g<-1>\g'-1'With named backreferences, we may also use the \k escape sequence as well as the (?P=...) construct. The following combinations also refer to the text matching the named capture group, as documented:\g{name}\k{name}\k<name>\k'name'(?P=name)However, these refer to the subpattern code instead of the matched text:g<name>\g'name'In the following example, the capture group searches for a single letter 'a' or 'b', and then the backreference looks for the same letter. Thus, the patterns are expected to match 'aa' and 'bb', but not 'ab' nor 'ba'.<?php$patterns = [ '/([ab])\1/', '/([ab])\g1/', '/([ab])\g{1}/', '/([ab])\g<1>/', "/([ab])\g'1'/", '/([ab])\k{1}/', '/([ab])\k<1>/', "/([ab])\k'1'/", '/([ab])(?P=1)/', '/([ab])\-1/', '/([ab])\g-1/', '/([ab])\g{-1}/', '/([ab])\g<-1>/', "/([ab])\g'-1'/", '/([ab])\k{-1}/', '/([ab])\k<-1>/', "/([ab])\k'-1'/", '/([ab])(?P=-1)/', '/(?<name>[ab])\g{name}/', '/(?<name>[ab])\g<name>/', "/(?<name>[ab])\g'name'/", '/(?<name>[ab])\k{name}/', '/(?<name>[ab])\k<name>/', "/(?<name>[ab])\k'name'/", '/(?<name>[ab])(?P=name)/', ]; foreach ($patterns as $pat) echo " '$pat',\t// " . var_export(@preg_replace($pat, 'xx', 'aa ab ba bb'), 1) . PHP_EOL;?>