phpregexreplacepreg-replacebackreference

Append text immediately after a regex match -- "$0$n" is misinterpreted by preg_replace()


I'm trying to append a number to another number

$n = 123;
$str = "some string with tt=789_ and more";
echo preg_replace("/tt=[0-9]+/", "$0$n", $str);

Desired result:

some string with tt=789_123 and more

Current result:

some string with 23_ and more

Solution

  • In your example the $0$n is transformed to $0123 which can confuse preg_replace (see the section about replacement).

    So the correct way is to do the following:

    $n = 123;
    $str = "some string with tt=789_ and more";
    echo preg_replace("/tt=[0-9_]+/", "\${0}$n", $str);
    

    I've also added _ to your character class otherwise it returns tt=789123_.