PHP replace only working once -
i have string containing html coming form ($postcontent). want assign unique id every image.
i have 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 first occurence of tag, rest not work.
further explaination:
<div><img src="http://image1"><img src="image2"></div>
after going trough code 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 idea problem might be?
your call strpos
finding first instance of <img
. need use third argument offset position of previous <img
, plus one. see manual entry strpos.
so me 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 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>
Comments
Post a Comment