开发者

PHP: preg_replace with unique replacement

开发者 https://www.devze.com 2023-02-07 04:45 出处:网络
I want to replace each instance of a given string with a number. ex: <?php $string = \"Hello Foo Text Apple\"

I want to replace each instance of a given string with a number.

ex:

<?php

$string = "Hello Foo Text Apple"
preg_replace($pattern, $pattern.$i++, $string);

//output    
Hello0 Foo1 Text2 Apple3

?>

the $pattern is a regex query but in this case I have 开发者_高级运维used plain text


If you are using PHP 5.3:

$string = "Hello Hello Hello Hello";
$i = 0;
preg_replace_callback($pattern, function($matches) use ($i) {
    return $matches[0].$i++;
}, $string);


$string = "Hello Hello Hello Test Hello Test";

$i = 0;
$string = preg_replace("/\w+/e", '$0 . $i++', $string);
0

精彩评论

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