I have an string with some <img> in it.
$string = ' <img src="pic.jpg"> and <img src="pic2.jpg">';
$doc = new DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$doc->loadHTML(mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img)
{
if($img->getAttribute('src') == 'pic.jpg')
{
// I want delete that picture form string
$img->parentNode->removeChild($img);
}
else
$img->setAttribute('class', 'image normall');
}
$string = $doc->saveHTML();
echo $string;
In the end of function when I print $string, the target pic has been delete but for other pic, no add any class to them!
but If I remove $img->parentNode->removeChild($img); , the class will add!
what's my wrong?
EDIT please check for this sample string:
$string = ' <img src="pic.jpg"> and <img src="pic2.jpg">';
if($img->getAttribute('src') == 'pic.jpg').... the code remove that pic...But unable to add class for other pic