簡體   English   中英

PHP從HTML中剝離img標簽,返回數組中的html和圖像

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM