在 CMS、編輯器、內容審核等場景,常需判斷 HTML 內容是否包含圖片。本文提供兩種方案:正則快速檢測(輕量、適用簡單場景)與 DOMDocument 解析(嚴謹、可提取屬性、過濾惡意標籤)。
<?php
function hasImage(string $html): bool {
// 模式:
// i: 不區分大小寫,s: . 匹配換行
return (bool) preg_match('/
]*\bsrc\s*=\s*["\']?[^"\'>\s]+/is', $html);
}
// 測試
$html1 = '文字內容

繼續文字
';
$html2 = '純文字內容,無圖片
';
$html3 = '
'; // 大寫、自閉合、Data URI
var_dump(hasImage($html1)); // true
var_dump(hasImage($html2)); // false
var_dump(hasImage($html3)); // true
:匹配 <img 開頭,單字邊界防止匹配 <image[^>]*:匹配任意非 > 字元(屬性區)\bsrc\s*=\s*["\']?:匹配 src 屬性,允許空白、單雙引號或無引號[^"\'>\s]+:匹配非引號、非 >、非空白的字元(URL 開頭)| 優點 | 缺點 |
|---|---|
| 極快、無依賴、單行代碼 | 無法處理惡意構造(如 <img src=x onerror=alert(1)>) |
| 可直接用於資料庫 WHERE 條件(MySQL REGEXP) | HTML 嵌套、註釋、腳本標籤內的 img 會誤判 |
| 無法提取 src、alt 等屬性值 |
<?php
function getImages(string $html): array {
$dom = new DOMDocument();
// 抑制 HTML5 非標準標籤警告
libxml_use_internal_errors(true);
// 載入 HTML 片段(指定編碼避免中文亂碼)
$dom->loadHTML('' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$images = [];
foreach ($dom->getElementsByTagName('img') as $img) {
$src = $img->getAttribute('src');
if ($src === '') continue; // 略過無 src
$images[] = [
'src' => $src,
'alt' => $img->getAttribute('alt'),
'width' => $img->getAttribute('width'),
'height' => $img->getAttribute('height'),
'class' => $img->getAttribute('class'),
'data_src' => $img->getAttribute('data-src'), // 懶加載常用
];
}
return $images;
}
// 使用
$images = getImages($htmlContent);
if (!empty($images)) {
echo "偵測到 " . count($images) . " 張圖片:\n";
foreach ($images as $img) {
echo " - {$img['src']} (alt: {$img['alt']})\n";
}
}
function filterSafeImages(array $images): array {
return array_filter($images, function($img) {
$src = $img['src'];
// 過濾 Data URI(編輯器產生的暫時圖片)
if (str_starts_with($src, 'data:')) return false;
// 過濾 1x1 像素追蹤圖
if (($img['width'] ?? 0) == 1 && ($img['height'] ?? 0) == 1) return false;
// 過濾已知追蹤域名
$trackDomains = ['tracker.com', 'analytics.com', 'pixel.'];
foreach ($trackDomains as $d) {
if (str_contains($src, $d)) return false;
}
return true;
});
}
| 方法 | 耗時 | 記憶體 | 準確度 |
|---|---|---|---|
| preg_match | ~0.15s | 極低 | 90% (誤判率較高) |
| DOMDocument | ~1.2s | 中等 | 99.9% (標準解析) |
preg_match 足夠,效能最佳DOMDocument 唯一正解XMLReader 流式解析或 Masterminds/HTML5 (Composer 套件)strip_tags($html, '
') !== $html 極簡但不精確