抓取 RSS/Atom feed、爬蟲抓取頁面、郵件模板渲染時,HTML 內的 `href="..."`、`src="..."` 常為相對路徑,需轉為絕對 URL 才能正確顯示或存檔。
function relative_to_absolute(string $content, string $feed_url): string {
// 1. 提取協議
if (!preg_match('#^(https?|ftp)://#i', $feed_url, $m)) return $content;
$protocol = $m[0]; // 如 "https://"
// 2. 提取主機部分 (不含 path)
$host = preg_replace('#^(https?|ftp)://#i', '', $feed_url);
$host = preg_replace('#/.*#', '', $host); // 截取第一個 / 前
if (!$host) return $content;
// 3. 替換 href/src 開頭的相對路徑
$base = $protocol . $host . '/';
$content = preg_replace('#(href|src)="([^"]*)"#i', function($m) use ($base) {
$url = $m[2];
// 已是絕對或協議相對則跳過
if (preg_match('#^(https?|ftp)://|^//#i', $url)) return $m[0];
// 以 / 開頭為根路徑相對,否則為當前目錄相對
$absolute = ($url[0] === '/') ? $protocol . $host . $url : $base . $url;
return $m[1] . '="' . $absolute . '"';
}, $content);
return $content;
}
$html = '<a href="article.html"><img src="/images/logo.png"><a href="https://other.com">';
$base = 'https://example.com/blog/feed.xml';
echo relative_to_absolute($html, $base);
// 輸出:
// <a href="https://example.com/blog/article.html">
// <img src="https://example.com/images/logo.png">
// <a href="https://other.com">