萬盛學電腦網

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

PHP 正則表達式提取/替換 img 標籤屬性完整指南

測試字串


$html = '<center><img src="/uploads/images/20100516000.jpg" height="120" width="120" alt="示例圖片"><br />PHP 正則處理 img 標籤</center>';

一、提取屬性

1. 取得完整 img 標籤


// 非貪婪匹配屬性,支援單雙引號、無引號
preg_match('/<img\s+[^>]*?src\s*=\s*([\'"])(.*?)\1[^>]*?\/?>/is', $html, $m);
echo $m[0]; // 完整標籤
echo $m[2]; // src 值

2. 提取 width


preg_match('/<img[^>]*\bwidth\s*=\s*([\'"]?)(\d+)\1/i', $html, $m);
echo $m[2]; // 120

3. 提取 height


preg_match('/<img[^>]*\bheight\s*=\s*([\'"]?)(\d+)\1/i', $html, $m);
echo $m[2]; // 120

4. 提取 src (支援多種圖片格式)


preg_match('/<img[^>]*\bsrc\s*=\s*([\'"])(.*?\.(?:jpg|jpeg|gif|png|bmp|webp))\1/i', $html, $m);
echo $m[2]; // /uploads/images/20100516000.jpg

5. 一次提取所有屬性 (陣列)


function extractImgAttributes(string $html): array {
    $attrs = [];
    if (preg_match('/<img\s+([^>]+)\/?>/is', $html, $m)) {
        // 解析屬性字串
        preg_match_all('/(\w+)\s*=\s*([\'"])(.*?)\2/', $m[1], $matches, PREG_SET_ORDER);
        foreach ($matches as $mat) {
            $attrs[$mat[1]] = $mat[3];
        }
    }
    return $attrs;
}

print_r(extractImgAttributes($html));
/*
Array
(
    [src] => /uploads/images/20100516000.jpg
    [height] => 120
    [width] => 120
    [alt] => 示例圖片
)
*/

二、替換/修改屬性

1. 替換 src 路徑 (加前綴)


// 將 /uploads/images/... 替換為 /uploads/uc/images/...
$newHtml = preg_replace(
    '/(<img[^>]*\bsrc\s*=\s*[\'"])(.*?)(images\/.*?\.(?:jpg|jpeg|gif|png|bmp|webp))([\'"][^>]*\/?>)/i',
    '${1}${2}uc/${3}${4}',
    $html
);

2. 替換 src 並移除 width/height


$newHtml = preg_replace(
    '/<img\s+([^>]*?)\bsrc\s*=\s*([\'"])(.*?)\2([^>]*?)\/?>/is',
    function($m) {
        $attrs = $m[1] . $m[4]; // 其他屬性
        // 移除 width/height
        $attrs = preg_replace('/\s+(width|height)\s*=\s*[\'"]\d+[\'"]/i', '', $attrs);
        // 修改 src
        $src = preg_replace('/(.*?)(images\/)/i', '${1}uc/${2}', $m[3]);
        return "<img {$attrs} src=\"{$src}\">";
    },
    $html
);

3. 統一加上 lazy loading


$newHtml = preg_replace(
    '/(<img\s+[^>]*\bsrc\s*=\s*[\'"][^\'"]+[\'"])/i',
    '$1 loading="lazy"',
    $html
);

三、現代最佳實務:DOMDocument (非正則)


function processImagesWithDom(string $html, callable $callback): string {
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML('' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();
    
    foreach ($dom->getElementsByTagName('img') as $img) {
        $callback($img); // 傳入 DOMElement 物件操作
    }
    
    $result = '';
    foreach ($dom->getElementsByTagName('body')->item(0)->childNodes as $node) {
        $result .= $dom->saveHTML($node);
    }
    return $result;
}

// 使用範例:修改 src、加入 loading、移除 width/height
$processed = processImagesWithDom($html, function($img) {
    if ($img->hasAttribute('src')) {
        $src = $img->getAttribute('src');
        $src = preg_replace('/(.*?)(images\/)/i', '${1}uc/${2}', $src);
        $img->setAttribute('src', $src);
    }
    $img->setAttribute('loading', 'lazy');
    $img->removeAttribute('width');
    $img->removeAttribute('height');
});

正則 vs DOMDocument 比較

維度正則表達式DOMDocument
速度極快較慢 (建構樹)
健壯性脆弱 (HTML 變動易錯)強健 (標準解析器)
屬性順序/格式敏感不敏感
巢狀/異常標籤難以處理自動修正
編碼處理手動處理自動處理
記憶體低高 (整份文檔)

建議

  • 簡單、固定格式、高效能需求 → 正則
  • 複雜 HTML、使用者輸入、需修改結構 → DOMDocument
  • 現代專案:考慮 masterminds/html5-php (HTML5 解析器) 或 symfony/dom-crawler
copyright © 萬盛學電腦網 all rights reserved