[英]PHP strip img tags from html, returning the html and the images in an array
我需要編寫一個帶有一些HTML的函數,去掉img標簽並返回html(沒有圖像)。 但是,我還需要保留imgs(在數組中),以便我可以單獨將它們輸出到頁面。
我幾乎不知道任何PHP所以最好的方法是什么?
您需要熟悉DOMDocument類 。 執行此操作的最佳方法是使用DOMDocument
解析HTML,並使用getElementsByTagName('img')
找到所有<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);
}
<?php
$pattern = '/<img[^>]*src="([^"]*)[^>]*>/i';
preg_match_all($pattern, $data, $matches);
// image src array
$images = $matches[1];
// no images
$html = preg_replace($pattern, '', $data);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.