在 CMS 系統、內容審核、編輯器輔助功能中,檢測 HTML 內容是否包含圖片是常見需求。本文從正則匹配、DOM 解析、性能考量三個維度,提供生產環境可用的最佳實踐方案。
<?php
function hasImageRegex(string $html): bool
{
// 匹配
標籤,支援單雙引號、屬性順序不固定、自閉合
$pattern = '/
]*\bsrc\s*=\s*["\']?([^"\'>\s]+)["\']?[^>]*>/i';
return (bool)preg_match($pattern, $html);
}
// 使用示例
$content = file_get_contents('https://example.com/article/123.html');
if (hasImageRegex($content)) {
echo "檢測到圖片";
} else {
echo "未發現圖片";
}
:匹配 img 標籤開頭,單詞邊界避免匹配 imgxyz[^>]*:匹配非 > 字符(屬性區域)\bsrc\s*=\s*["\']?:匹配 src 屬性,允許空格、單雙引號([^"\'>\s]+):捕獲圖片 URL(排除引號、>、空白)<?php
function hasImageDom(string $html): bool
{
libxml_use_internal_errors(true); // 抑制 HTML5 非標準標籤警告
$dom = new DOMDocument();
$dom->loadHTML('' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$images = $dom->getElementsByTagName('img');
foreach ($images as $img) {
$src = $img->getAttribute('src');
if ($src !== '') {
return true;
}
}
return false;
}
當處理超大 HTML(>1MB)且僅需判斷是否存在時,避免完整載入內存:
<?php
function hasImageStream(string $filePath): bool
{
$handle = fopen($filePath, 'r');
if (!$handle) return false;
$bufferSize = 8192;
$overlap = 100; // 確保跨緩衝區匹配
$prevTail = '';
while (!feof($handle)) {
$chunk = fread($handle, $bufferSize);
$searchArea = $prevTail . $chunk;
if (preg_match('/
]*\bsrc\s*=\s*["\']?[^"\'>\s]+["\']?[^>]*>/i', $searchArea)) {
fclose($handle);
return true;
}
$prevTail = substr($chunk, -$overlap);
}
fclose($handle);
return false;
}
<?php
function extractImages(string $html): array
{
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML('' . $html);
libxml_clear_errors();
$images = [];
foreach ($dom->getElementsByTagName('img') as $img) {
$images[] = [
'src' => $img->getAttribute('src'),
'alt' => $img->getAttribute('alt'),
'width' => $img->getAttribute('width'),
'height' => $img->getAttribute('height'),
'data_src' => $img->getAttribute('data-src'), // 延遲加載
'class' => $img->getAttribute('class'),
];
}
return $images;
}
防止中文亂碼libxml_use_internal_errors(true) 避免非標準 HTML 產生警告parse_url() 和基礎 URL 補全data-src、data-original 等屬性background-image,需解析 style 屬性或 <style> 標籤對於多數 CMS 應用,正則方案足夠高效且代碼簡潔;當需要提取圖片屬性、處理異常 HTML 或構建內容審核系統時,DOMDocument 是專業選擇。根據業務場景選擇合適方案,並注意編碼、錯誤處理、性能優化三大維度。