georg
georg

Reputation: 214969

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

Upvotes: 0

Views: 780

Answers (2)

mickmackusa
mickmackusa

Reputation: 47903

This is effectively an XY Problem. You are trying to figure out how to access the fullstring match from the regex in the replacement parameter. The truth is, if you end your regex with \K, this will "forget" the matched string and therefore not consume those characters in the replacement. Below is the simpler implementation. (Demo)

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

Upvotes: 0

vstm
vstm

Reputation: 12537

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_.

Upvotes: 4

Related Questions