從 HTML 內容中精準提取 `` 標籤的 `src` 屬性值,是爬蟲、內容遷移、編輯器圖片管理的常見需求。本文從正則基礎、常見陷阱、邊界情況處理到最佳實踐,提供生產環境可用的完整方案。
<img src="https://example.com/photo.jpg" alt="風景" title="標題" width="800" height="600" class="img-responsive">
<img src='/upload/2024/01/avatar.png' data-id="123">
<img src=//cdn.example.com/image.webp loading="lazy">
<img data-src="lazy.jpg" src="placeholder.gif"> <!-- 懶加載 -->
挑戰:屬性順序不固定、單雙引號混用、無引號、屬性值含特殊字元、懶加載 `data-src`、相對/絕對/協定相對路徑。
// 僅匹配 src="..." 固定順序
'/<img[^>]+src="([^"]+)"/i'
❌ 失敗:單引號、無引號、src 不在第一個屬性。
"/
]+src\s*=\s*(['\"])([^'\"]+)\\1/i"
// \\1 反向引用確保引號配對
❌ 失敗:無引號屬性值、src 前有其他屬性時貪婪匹配錯誤。
"/
]*\\bsrc\\s*=\\s*(?:(['\"])([^'\"]+)\\1|([^\\s>]+))/i"
// 非捕獲群組 (?:...),三種情況:雙引號、單引號、無引號
⚠️ 仍有問題:無法處理屬性值含 `>`、編碼實體、跨行標籤。
<?php
function extractImageUrls(string $html, array $options = []): array
{
$opts = array_merge([
'include_lazy' => true, // 是否包含 data-src 等懶加載屬性
'absolute_base' => null, // 相對轉絕對路徑的基礎 URL
'unique' => true, // 去重
], $options);
// 核心正則:匹配 img 標籤中的 src (及可選 data-src)
// 使用具體字元類別而非 .*?,避免災難性回溯
$pattern = '
/
]*? # 非貪婪匹配非 > 字元 (其他屬性)
\\b(src|data-src)\\s*=\\s* # 目標屬性名 + 等號 + 空白
(?: # 非捕獲群組:三種引號情況
"([^"]*)" # 雙引號內容 -> $2
| \'([^\']*)\' # 單引號內容 -> $3
| ([^\\s>]+) # 無引號內容 -> $4
)
[^>]* # 剩餘屬性
> # 結尾 >
/ix # i:忽略大小寫 x:忽略模式空白可讀性
';
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
$urls = [];
foreach ($matches as $m) {
// $m[2] 雙引號、$m[3] 單引號、$m[4] 無引號
$url = $m[2] ?? $m[3] ?? $m[4] ?? '';
if ($url === '') continue;
// 解碼 HTML 實體 (& -> &, ' -> ')
$url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
// 相對路徑轉絕對
if ($opts['absolute_base'] && !preg_match('~^https?://~i', $url)) {
$base = rtrim($opts['absolute_base'], '/');
$url = $base . '/' . ltrim($url, '/');
}
$urls[] = $url;
}
if ($opts['unique']) {
$urls = array_values(array_unique($urls));
}
return $urls;
}
<?php
$html = file_get_contents('https://example.com/article.html');
$images = extractImageUrls($html, [
'include_lazy' => true,
'absolute_base' => 'https://example.com',
'unique' => true,
]);
print_r($images);
/*
Array
(
[0] => https://example.com/photo.jpg
[1] => https://example.com/upload/2024/01/avatar.png
[2] => https://cdn.example.com/image.webp
[3] => https://example.com/lazy.jpg
)
*/
<?php
function extractImagesDom(string $html, string $baseUrl = ''): array
{
$dom = new DOMDocument();
libxml_use_internal_errors(true); // 抑制 HTML5 解析警告
$dom->loadHTML('' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
$urls = [];
// 同時查找 src 和 data-src
foreach (['@src', '@data-src'] as $attr) {
$nodes = $xpath->query("//img[$attr]");
foreach ($nodes as $img) {
$url = $img->getAttribute($attr);
if ($url === '') continue;
// 相對轉絕對
if ($baseUrl && !preg_match('~^https?://~i', $url)) {
$url = rtrim($baseUrl, '/') . '/' . ltrim($url, '/');
}
$urls[] = $url;
}
}
return array_values(array_unique($urls));
}
| 維度 | 正則表達式 | DOMDocument + XPath |
|---|---|---|
| 解析正確性 | 邊界情況易出錯 | 標準 HTML 解析器,正確率極高 |
| 效能 (小型 HTML) | 極快 | 稍慢 (建構 DOM 樹) |
| 效能 (大型 HTML > 1MB) | 記憶體較低 | 記憶體較高 |
| 容錯性 (不合法 HTML) | 視模式而定 | libxml 自動修補,極強 |
| 提取屬性靈活度 | 極高 | 高 (XPath 強大) |
| 相依性 | 零相依 | 需 PHP xml 擴充 (通常內建) |