preg_replace remove my first digit for no reason :(

Is this a bug? Anyone have any idea?

$var = '9gag.com/gag/144972/';
$test1 = '<a href="http://9gag.com/gag/144972/" target="_blank"></a>';

$test1 = preg_replace('#(<a href="(\\w+://)?([' . preg_quote( $var ) . ']+)"[^>]+>)(</a>)#', "\\\\1$var\\\\4", $test1 );
echo $test1;

If the first character is a digit, preg_replace seems to always removes it! :frowning:

put a space between the \\1 and the $var.

I see, thanks a million StarLion!

This is already covered in the manual, which I’m going to assume you’ve read.

In your case, the replacement string is sent to preg_replace() as "\\19gag.com/gag/144972/\\4", which it reads as “backreference 19, literal gag.com/gag/144972/ then backreference 4.” The solution, as the docs say, would be to make your string like "${1}$var$4".

THanks Salathe, I did read the part you’ve highlighted on the manual but I put it the wrong position like so:

\\1{$var}\\4

Lol, dumb me but thanks for your input. Got it working! \${1}