PHP: preg_replace with unique replacement
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);
精彩评论