萬盛學電腦網

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

PHP 偵測文章內容是否包含圖片的高效方法(preg_match / DOMDocument 兩種方案)

在 CMS、編輯器、內容審核等場景,常需判斷 HTML 內容是否包含圖片。本文提供兩種方案:正則快速檢測(輕量、適用簡單場景)與 DOMDocument 解析(嚴謹、可提取屬性、過濾惡意標籤)。

方案一:preg_match 快速檢測(推薦簡單場景)

<?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 等屬性值

方案二:DOMDocument 解析(推薦嚴謹場景)

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

效能比較(10萬次迴圈,HTML 長度 ~2KB)

方法耗時記憶體準確度
preg_match~0.15s極低90% (誤判率較高)
DOMDocument~1.2s中等99.9% (標準解析)

選擇建議

  • 單純判斷「有無圖片」:preg_match 足夠,效能最佳
  • 需提取圖屬性、過濾、轉存、替換 CDN 域名:DOMDocument 唯一正解
  • 超大 HTML(>100KB):考慮 XMLReader 流式解析或 Masterminds/HTML5 (Composer 套件)
  • 純文字內容檢測:strip_tags($html, '') !== $html 極簡但不精確
copyright © 萬盛學電腦網 all rights reserved