Search code examples
phpreplacestrpos

PHP replace only working once


I have a string containing html coming from a form ($postContent). I want to assign a unique id to every image.

I have the following code:

$numImages=substr_count($postContent, '<img');
for($o=0; $o<$numImages; $o++){
  $pos = strpos($postContent,"<img");
  $postContent = substr_replace($postContent,"<img id='$o' height='50px' onclick='resize(\"$o\")' ",$pos,4);
}

It works fine for the first occurence of an tag, but for the rest it does not work.

Further explaination:

<div><img src="http://image1"><img src="image2"></div>

after going trough my code it gives this:

<div>
<img id='1' height='50px' onclick='resize("1")'  id='0' height='50px'
onclick='resize("0")'  src="http://image1"><img src="http://image2"></div>

Anyone has any idea what the problem might be?


Solution

  • Your call to strpos is always finding the first instance of <img. You need to use the third argument to offset it by the position of the previous <img, plus one. See the manual entry for strpos.

    So for me this code worked:

    $postContent = '<div><img src="http://image1"><img src="image2"><img src="image3"></div>';
    $numImages=substr_count($postContent, '<img');
    $last_pos = 0;
    for($o=0; $o<$numImages; $o++){
      $pos = strpos($postContent,"<img",$last_pos+1);
      $postContent = substr_replace($postContent,"<img id='$o' height='50px' onclick='resize(\"$o\")' ",$pos,4);
      $last_pos = $pos;
    }
    echo htmlentities($postContent);
    

    Which produces this output:

    <div><img id='0' height='50px' onclick='resize("0")' src="http://image1"><img id='1' height='50px' onclick='resize("1")' src="image2"><img id='2' height='50px' onclick='resize("2")' src="image3"></div>