首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 將相對路徑轉為絕對 URL:從 Gregarius 移植的通用函數

     編輯:PHP 相關知識

使用場景

抓取 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;
}

關鍵改進點 (對比原版)

  • 使用 `preg_replace_callback` 一次性處理 `href`/`src`,避免多次遍歷。
  • 正確識別協議相對 URL (`//example.com/path`)、根路徑相對 (`/path`)、當前目錄相對 (`path`)。
  • 跳過已為絕對 URL 的屬性,避免重複拼接。
  • 嚴格型別聲明,符合 PHP 7+ 標準。

測試用例

$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">

擴展建議

  • 支援 `` 標籤優先級。
  • 處理 CSS `url(...)`、JS 動態拼接路徑 (需 DOM 解析器)。
  • 大規模處理時改用 `DOMDocument` + `DOMXPath`,更健壯但較慢。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved