我正在尝试从HTML字符串中删除所有图像。我只能删除第一个,但我不知道为什么。
代码:
<?php
$str='<div>
<a href=
"https://www.google.com">
<img src=
"image1.jpg"
alt="image-1.jpg" /></a>
</div>
<p>
hobby\'s vs hobbies
</p>
<div>
<a href=
"https://www.google.com">
<img src=
"image2.jpg"
alt="image-2.jpg" /></a>
</div>';
$dom=new domDocument;
$dom->loadHTML($str);
$images=$dom->getElementsByTagName('img');
foreach($images as $image)
{
$image->parentNode->removeChild($image);
}
$result=$dom->saveHTML();
echo '<textarea>'.$result.'</textarea>';
?>
检查Marco Gamba答案
// ...loading the DOM
$dom = new DOMDocument();
@$dom->loadHTML($string); // Using @ to hide any parse warning sometimes resulting from markup errors
$dom->preserveWhiteSpace = false;
// Here we strip all the img tags in the document
$images = $dom->getElementsByTagName('img');
$imgs = array();
foreach($images as $img) {
$imgs[] = $img;
}
foreach($imgs as $img) {
$img->parentNode->removeChild($img);
}
$str = $dom->saveHTML();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句