I have this html in my database:
<p>some text 1</p>
<img src=\"http://www.example.com/images/some_image_1.jpg\">
<p>some text 2</p>
<p>some text 3</p>
<img src=\"http://www.example.com/images/some_image_2.jpg\">
<p>some text 4</p>
<p>some text 5</p>
<img src=\"http://www.example.com/images/some_image_3.jpg\">
Conditionally, I need to remove some specific <img>
tag. So I don't want to remove all <img>
tags, but only specific ones.
I have tried this, but it will remove all <img>
tags, even if I do not want that:
$dom = new \DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName("img");
for($i = 0; $i < $nodes->length; $i++) {
if ($i == 1) {
continue;
}
$image = $nodes->item($i);
$image->parentNode->removeChild($image);
}
return $dom->saveHTML();
Can someone help me with this ? In this html example, let's say that I want to remove first and third image in text, but to leave second one.
Also, I have noticed that saveHTML()
method is adding <html><body>
tags to my html, and I do not want that. I don't see any option to turn this off. Any help there too ?
Thanks in advance, I'm stuck with this for hours.