PHP从HTML中剥离img标签,返回数组中的html和图像
发布时间:2020-12-13 21:40:32 所属栏目:PHP教程 来源:网络整理
导读:我需要编写一个带有一些 HTML的函数,去掉img标签并返回html(没有图像).但是,我还需要保留imgs(在数组中),以便我可以单独将它们输出到页面. 我几乎不知道任何PHP所以最好的方法是什么? 解决方法 您需要熟悉 DOMDocument class.执行此操作的最佳方法是使用DOM
我需要编写一个带有一些
HTML的函数,去掉img标签并返回html(没有图像).但是,我还需要保留imgs(在数组中),以便我可以单独将它们输出到页面.
我几乎不知道任何PHP所以最好的方法是什么? 解决方法
您需要熟悉
DOMDocument class.执行此操作的最佳方法是使用DOMDocument解析HTML,并找到所有< img>标签使用getElementsByTagName(‘img’).如果它是你所追求的图像的src属性,DOMDocument可以返回它们并存储在数组中.
// HTML already parsed into $dom $imgs = $dom->getElementsByTagName('img'); $img_src = array(); // Array of nodes to remove. $to_remove = array(); foreach ($imgs as $img) { // Store the img src $img_src[] = $img->getAttribute('src'); // Delete the node (I think this works) $to_remove[] = $img; } // Then remove all the nodes slated for deletion: foreach ($to_remove as $node) { $dom->removeChild($img); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |