Zebra
Zebra

Reputation: 4006

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

Upvotes: 0

Views: 385

Answers (2)

user142162
user142162

Reputation:

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

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

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

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);

Upvotes: 2

Related Questions