萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 正則表達式提取圖片網址:從基礎到進階的完整實戰指南

從 HTML 內容中精準提取 `` 標籤的 `src` 屬性值,是爬蟲、內容遷移、編輯器圖片管理的常見需求。本文從正則基礎、常見陷阱、邊界情況處理到最佳實踐,提供生產環境可用的完整方案。

目標 HTML 結構分析

<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`、相對/絕對/協定相對路徑。

正則演進歷程

階段 1:簡單但脆弱

// 僅匹配 src="..." 固定順序
'/<img[^>]+src="([^"]+)"/i'

❌ 失敗:單引號、無引號、src 不在第一個屬性。

階段 2:支援單雙引號

"/]+src\s*=\s*(['\"])([^'\"]+)\\1/i"
// \\1 反向引用確保引號配對

❌ 失敗:無引號屬性值、src 前有其他屬性時貪婪匹配錯誤。

階段 3:非貪婪 + 多屬性順序

"/]*\\bsrc\\s*=\\s*(?:(['\"])([^'\"]+)\\1|([^\\s>]+))/i"
// 非捕獲群組 (?:...),三種情況:雙引號、單引號、無引號

⚠️ 仍有問題:無法處理屬性值含 `>`、編碼實體、跨行標籤。

階段 4:生產級強健正則 (推薦)

<?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
)
*/

進階:使用 DOMDocument (更穩健、標準做法)

<?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));
}

正則 vs DOMDocument 選擇指南

維度正則表達式DOMDocument + XPath
解析正確性邊界情況易出錯標準 HTML 解析器,正確率極高
效能 (小型 HTML)極快稍慢 (建構 DOM 樹)
效能 (大型 HTML > 1MB)記憶體較低記憶體較高
容錯性 (不合法 HTML)視模式而定libxml 自動修補,極強
提取屬性靈活度極高高 (XPath 強大)
相依性零相依需 PHP xml 擴充 (通常內建)

最佳實踐建議

  1. 首選 DOMDocument:正確性優先,維護成本低
  2. 效能敏感/簡單場景:使用經過充分測試的正則
  3. 爬蟲專案:搭配 Symfony DomCrawler 或 PHP HTML Parser
  4. 防禦性編程:永遠 `html_entity_decode`、驗證 URL 格式、限制大小、設定超時
copyright © 萬盛學電腦網 all rights reserved