views:

56

answers:

1

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

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

+5  A: 

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.

e-t172