0

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?

Rumanoid
  • 139
  • 1
  • 3
  • 15

2 Answers2

1

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>
GluePear
  • 7,244
  • 20
  • 67
  • 120
1

Rather than modifying HTML via the replace methods, you can also modify it safely using the DOMDocument object

$postDocument = new DOMDocument();
$postDocument->loadHTML($postContent);

$images = $postDocument->getElementsByTagsName('img');

for($i = 0; $i < $images->length; $i++) {
    $element = $images->item($i);
    $element->setAttribute('id', $i);
    $element->setAttribute('height', '50px');
    $element->setAttribute('onclick', 'resize("0")');
}

$postContent = $postDocument->saveHTML();

In this way, you don't have to worry whether or not your img tags that you have selected have the attributes defined or not.

It also will allow you to easily add new attributes. And it avoids the slippery slope of using regex on html as in this answer.

Community
  • 1
  • 1
Schleis
  • 41,516
  • 7
  • 68
  • 87
  • Thank you, I accepted GluePear's answer because it is closer to the situation I had, but thanks anyway – Rumanoid Aug 19 '15 at 18:01