What I would like is to replace every occurrence of a string with another string followed by a number which increments after each string found.

So if I was trying to find "href" I would want it to replace each one like the following:

first occurrence: href1
second occurrence: href2
third occurrence: hre3

So I have tried this:

$i=0;
$comments = str_replace("href", "href".++$i."", $comments);

But it doesn't work.

How would I go about doing this?

    Looks like you need some sort of loop - maybe try and count the amount of occurrence of href and loop that many times adding 1 to x every time?

      You could use preg_replace with the "e" modifier:

      <?php
      $test = "foo bar foo bar foo bar";
      $i = 1;
      echo preg_replace('/bar/e', '"BAR ".$i++', $test);
      // outputs: foo BAR 1 foo BAR 2 foo BAR 3
      ?>
      
        Write a Reply...