The difference between $1 and \1?

May someone please explain the difference between using $1 and \1 in this scenario?

<?php
$text = "You know I mean *seriously*!";
$newText = preg_replace('/\*([^\*]+)\*(!)/','$2<em>$1</em>', $text);
echo $newText;

Explanations on the net are a bit mind-boggling, I’m getting similar results using either $ or \ in the code above anyway.
Thanks in advance.

They refer to the capture groups in your regex expression, which are denoted by (). The first captures [^*]+ and the second captures !

No I think you have misunderstood what I’m asking about here :thinking: I’ve used $2<em>$1</em> in the above code but I’m asking how would it be different if I used \2<em>\1</em> instead? I see no obvious difference between them and they both “apparently” seem to be the same…

They are “back references”
http://php.net/manual/en/regexp.reference.back-references.php

AFAIK, for PHP at least
http://php.net/manual/en/function.preg-replace.php

replacement may contain references of the form \\n or $n, with the latter form being the preferred one.

I’m guessing the backslash way is like a “go get it” and the dollar sign way is more like a “use what’s already in memory”. In other words, though the end result is the same the latter is more efficient.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.