<img title="alt文字" src="https://example.com/img.jpg" alt="描述" width="100" height="100" />
// PHP 不支援不定長度 lookbehind (?<=img.+?src=").*?(?=") // Compilation failed
(?<=img src=").*?(?=") (?<=img\s+src=").*?(?=")
$pattern = '/<img(.*?)src="(.*?)(?=")/'; preg_match_all($pattern, $html, $matches); // $matches[2] 為圖片地址陣列
$pattern = '/<img(.*?)src="(.*?\.(jpg|jpeg|gif|png|bmp))/i';
⚠️ 會漏掃無副檔名圖片(如 CDN 動態圖片)
function normalize_img_url(string $src, string $baseUrl): string {
if (preg_match('/^https?:\/\//', $src)) return $src; // 已是絕對
$base = rtrim($baseUrl, '/') . '/';
if ($src[0] === '/') {
// 根相對路徑
$parsed = parse_url($baseUrl);
return $parsed['scheme'] . '://' . $parsed['host'] . $src;
}
// 相對路徑:直接拼接(多層 / 瀏覽器自動正規化)
return $base . ltrim($src, './');
}
# 多重斜線等價 https://img.example.com/pics/nav/logo.png https://img.example.com////pics////nav///logo.png # 同樣可訪問
https://xyark.serw5.com/img.phphttps://xyark.serw5.com/g.php