萬盛學電腦網

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

PHP 智慧型 URL 轉超連結:保護既有 A/IMG 標籤、支援多協議、效能優化

將純文字中的 URL 自動轉為可點擊連結,同時不破壞既有 HTML 標籤(A、IMG 等),是常見需求(留言板、聊天室、CMS)。本文提供健壯的實作策略:標籤保護 → URL 轉換 → 標籤還原。

核心策略:三階段處理

  1. 保護:將既有 ``、``、``、`
    ` 等標籤替換為佔位符
  2. 轉換:對純文字部分的 URL 套用正則轉換
  3. 還原:將佔位符換回原始標籤

完整實作(支援 HTTP/HTTPS/FTP/WWW/郵件)

<?php
/**
 * 智慧型 URL 轉連結
 * @param string $text 輸入文字(可含 HTML)
 * @param array $options 選項
 * @return string 處理後 HTML
 */
function autoLinkUrls(string $text, array $options = []): string {
    $opts = array_merge([
        'target'      => '_blank',
        'rel'         => 'noopener noreferrer',
        'maxLength'   => 60,           // 顯示文字最大長度,超過截斷
        'protocols'   => ['http', 'https', 'ftp', 'ftps'],
        'email'       => true,         // 是否轉換 email
        'protectedTags' => ['a', 'img', 'code', 'pre', 'script', 'style'],
    ], $options);

    // 階段 1:保護既有標籤
    $placeholders = [];
    $protectedTags = $opts['protectedTags'];
    $placeholderPrefix = "\x00AUTOLINK_";
    $placeholderSuffix = "_\x00";

    foreach ($protectedTags as $tag) {
        $pattern = $tag === 'img' 
            ? '/]*>/i' 
            : "/<$tag\b[^>]*>.*?<\/$tag>/is";
        $text = preg_replace_callback($pattern, function($m) use (&$placeholders, $placeholderPrefix, $placeholderSuffix) {
            $key = $placeholderPrefix . count($placeholders) . $placeholderSuffix;
            $placeholders[$key] = $m[0];
            return $key;
        }, $text);
    }

    // 階段 2:URL 正則轉換
    $protocols = implode('|', array_map('preg_quote', $opts['protocols']));
    $urlRegex = <<"'])                            # 邊界:開頭、空白、>、引號
    (
        (?:{$protocols}://|www\.)             # 協議或 www.
        [^\s<>"'()]+                          # 非空白/標籤/引號/括號
        (?:\([^\s<>"'()]*\)|[^\s<>"'.,;:!?)])* # 允許括號內容、排除尾部標點
    )
~x
REGEX;

    $text = preg_replace_callback($urlRegex, function($m) use ($opts) {
        $url = $m[1];
        $display = $url;
        if (strlen($display) > $opts['maxLength']) {
            $display = mb_substr($display, 0, $opts['maxLength']) . '…';
        }
        // 補全協議
        if (str_starts_with($url, 'www.')) $url = 'https://' . $url;
        $attrs = "href=\"" . hAttr($url) . "\"";
        if ($opts['target']) $attrs .= " target=\"" . hAttr($opts['target']) . "\"";
        if ($opts['rel'])    $attrs .= " rel=\"" . hAttr($opts['rel']) . "\"";
        return "$display";
    }, $text);

    // Email 轉換
    if ($opts['email']) {
        $text = preg_replace_callback(
            '/(^|[\s\>"\'])([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+)(?=[\s<"\']|$)/',
            fn($m) => $m[1] . '' . h($m[2]) . '',
            $text
        );
    }

    // 階段 3:還原受保護標籤
    return strtr($text, $placeholders);
}

function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function hAttr(string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

測試案例

<?php
$input = <<舊連結 不應被改變。
圖片:圖片 也不應動。
郵件:contact@example.com
長網址:https://very-long-domain-name.example.com/path/to/resource?query=value#fragment
HTML;

echo autoLinkUrls($input);

輸出結果

請訪問 https://example.com 查看詳情。
現有連結:舊連結 不應被改變。
圖片:圖片 也不應動。
郵件:contact@example.com
長網址:https://very-long-domain-name.example.com/path/to/resource?query=value#fragme…

效能優化建議

  • 預編譯正則:靜態變數快取 `$urlRegex`,避免重複編譯
  • 限制長度:`maxLength` 避免超長 URL 撐破版面
  • 快取結果:相同內容可用 MD5 快取輸出
  • 大量文字分塊:超過 100KB 文字分段處理,避免 PCRE 回溯爆炸

替代方案:成熟庫

  • league/html-to-markdown + league/commonmark:Markdown → HTML 管線內建自動連結
  • voku/HtmlMin:包含連結轉換功能
  • Textile / BBCode 解析器:若用輕量標記語言
copyright © 萬盛學電腦網 all rights reserved