在 CMS 內容處理、編輯器過濾、圖片遷移等場景中,常需從 HTML 字串中精準提取或修改 <img> 標籤的特定屬性。本文系統整理常用正則模式,並說明邊界情況與最佳實踐。
$html = '<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP正則提取或更改圖片img標記中的任意屬性</center>';
// 模式:從 <img 開始匹配到 > 結束,支援單雙引號
$pattern = '/<img\s+[^>]*?src\s*=\s*([\'"\s])(.*?)\\1[^>]*?\/?\s*>/i';
preg_match($pattern, $html, $match);
echo $match[0]; // 輸出完整標籤
// 專門匹配常見圖片格式
$pattern = '/<img\s+[^>]*?src\s*=\s*[\'"\s]([^\'"\s]+\.(?:jpg|jpeg|gif|png|bmp|webp))[\'"\s]/i';
preg_match($pattern, $html, $match);
echo $match[1]; // /uploads/images/20100516000.jpg
// 寬度
preg_match('/<img\s+[^>]*?width\s*=\s*[\'"\s]?(\d+)[\'"\s]?/i', $html, $m);
echo $m[1]; // 120
// 高度
preg_match('/<img\s+[^>]*?height\s*=\s*[\'"\s]?(\d+)[\'"\s]?/i', $html, $m);
echo $m[1]; // 120
function getImgAttr($html, $attr) {
$pattern = sprintf(
'/<img\s+[^>]*?%s\s*=\s*([\'"\s])(.*?)\\1/i',
preg_quote($attr, '/')
);
return preg_match($pattern, $html, $m) ? $m[2] : null;
}
// 使用範例
echo getImgAttr($html, 'src'); // 圖片路徑
echo getImgAttr($html, 'alt'); // 替代文字 (若有)
echo getImgAttr($html, 'class'); // CSS 類別
// 將 /images/ 替換為 /uc/images/
$new_html = preg_replace(
'/(<img\s+[^>]*?src\s*=\s*[\'"\s])([^\'"\s]*images\/)([^\'"\s]+)/i',
'${1}${2}uc/${3}',
$html
);
// 移除 width 與 height
$clean_html = preg_replace(
'/\s+(width|height)\s*=\s*[\'"\s]\d+[\'"\s]/i',
'',
$html
);
$responsive_html = preg_replace(
'/(<img\s+)([^>]*?)(>)/i',
'${1}${2} class="img-responsive"${3}',
$html
);
正則處理 HTML 存在邊界風險 (巢狀標籤、屬性順序、註解等)。現代 PHP 建議使用 DOMDocument:
$dom = new DOMDocument();
libxml_use_internal_errors(true); // 忽略 HTML5 標籤警告
$dom->loadHTML('<meta charset="utf-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$images = $dom->getElementsByTagName('img');
foreach ($images as $img) {
// 讀取屬性
$src = $img->getAttribute('src');
$width = $img->getAttribute('width');
// 修改屬性
$img->setAttribute('src', str_replace('/images/', '/uc/images/', $src));
$img->removeAttribute('width');
$img->removeAttribute('height');
$img->setAttribute('class', 'img-fluid');
}
// 輸出修改後的 HTML
$new_html = $dom->saveHTML($dom->getElementsByTagName('body')->item(0));
| 場景 | 推薦方式 | 理由 |
|---|---|---|
| 簡單單一屬性提取 | 正則 | 輕量、快速、無依賴 |
| 複雜結構修改/多屬性操作 | DOMDocument | 語義正確、容錯率高、可維護 |
| 大量資料批次處理 | 正則 + 預編譯 | 記憶體佔用低、速度快 |
| 使用者輸入內容過濾 | HTMLPurifier | XSS 防護完整、白名單機制 |
.*? 非貪婪模式,避免跨標籤匹配src 不一定在第一個,用 [^>]*? 任意順序匹配<img ...> 與 <img ... /> 兩種寫法u 修飾符,確保 UTF-8 正確匹配正則表達式在簡單、固定格式的 img 標籤處理上極為高效;但面對複雜、不可控的 HTML 內容時,DOMDocument 提供更穩健的語義級操作。實務上可根據資料來源可信度與處理複雜度靈活選擇。