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?

1
  • Perhaps a regex will help out. Commented Aug 19, 2015 at 16:42

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thank you, I accepted GluePear's answer because it is closer to the situation I had, but thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.