ThatsMe
ThatsMe

Reputation: 7

replace reoccuring text in a string differently

I have the String $myString and the content of the String is random times "foo", but I don't know how many times!
What I want to do is to add an unique number to every "foo".
For example: "foo foo foo" -> "foo1 foo2 foo3"

my current approach: $z = 0; $myString = preg_replace ( '/foo/' , 'foo'.++$z, $myString);
and this returns of course "foo1 foo1 foo1"

So my questions is: How do I replace reoccuring text in a string differently in PHP?

Thank you!
MasterBolle

Upvotes: 0

Views: 48

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

To do it with regex the way is to use preg_replace_callback (there are a lot of examples in the PHP manual and SO).

Without regex, using explode and array_reduce:

$str = 'foosdfdsfdsfdfoofoosdfdsfdfoosdfoo';
$cnt = 0;
$result = array_reduce(explode('foo', $str), function($c,$i) use (&$cnt) {
    return $c === false ? $i : $c . 'foo' . ++$cnt . $i;
}, false);

Upvotes: 0

splash58
splash58

Reputation: 26153

$myString = 'foo foo foo';
$i = 1;
echo $myString = preg_replace_callback ( '/foo/', 
                 function($str) use (&$i) {return $str[0].$i++; }, 
                 $myString); // foo1 foo2 foo3

demo

Upvotes: 1

thefallen
thefallen

Reputation: 9749

You can count the occurrences of the word foo in your string and then add them with a number to each foo by looping the number of occurrences:

    $myString = 'foo foo foo';
    $counts = substr_count($myString, 'foo');
    $newString = '';

    for ($i = 1; $i <= $counts; $i++) {
        $newString .= 'foo' . $i . ' ';
    }

Upvotes: 1

Related Questions