phpregexpreg-replacebackreferencecapture-group

What's the difference between \1 versus $1 in the second paramter of preg_replace()?


In PHP, what is the difference between using \1 or $1 in the $replacement parameter of preg_replace()?

They both work and seem to do the exact same thing, but I think I'm missing something here.


Solution

  • You're not missing anything. There is only one situation where $n only can be used:

    When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \1 notation for your backreference. \11, for example, would confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

    Aside from that, there is absolutely no difference between the two.