开发者

preg replace placeholders

开发者 https://www.devze.com 2023-04-12 17:25 出处:网络
I\'m trying to append a 开发者_StackOverflow社区number to another number $n = 123; $str = \"some string with tt=789_ and more\";

I'm trying to append a 开发者_StackOverflow社区number to another number

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

I expect this to print "some string with tt=789_123 and more" for some reason i'm getting "some string with 23_ and more".


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号