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

PHP 自動將文本中 URL 轉為可點擊鏈接:autolink() 輕量級函數分享

     編輯:PHP 綜合知識

一個 20 行的 autolink() 函數,利用正則識別文本中的 HTTP/HTTPS/FTP/FTPS 鏈接並自動包裝為 <a> 標籤,支持自定義屬性(如 target="_blank"、rel="nofollow")。

函數源碼

/&**
 * Author: SeeDZ
 * From: https://code.seebz.net/p/autolink-php/
 *&/
function autolink($str, $attributes = [])
{
    $attrs = '';
    foreach ($attributes as $attribute => $value) {
        $attrs .= " {$attribute}=\"{$value}\"";
    }

    $str = ' ' . $str; // 前置空格保證開頭 URL 也能匹配
    $str = preg_replace(
        '`([^"\'>])((http|https|ftp|ftps)://[^\s<]+[^\s<.)])`i',
        '$1<a href="$2" rel="external nofollow" ' . $attrs . '>$2</a>',
        $str
    );
    $str = substr($str, 1); // 移除前置空格
    return $str;
}

正則解析

([^"'>])          # 匹配前一字符非引號/尖括號(避免已在標籤內)
((http|https|ftp|ftps)://  # 協議
 [^\s<]+           # 非空白非 < 字符(貪婪匹配主體)
 [^\s<.)]          # 結尾非空白/尖括號/點/括號(避免吞噬標點)
)`i                # 忽略大小寫

調用示例

<?php
// 1. 基礎用法
$str = 'A link: https://example.com/?param=value#anchor.';
echo autolink($str);
// 輸出: A link: <a href="https://example.com/?param=value#anchor" rel="external nofollow">https://example.com/?param=value#anchor</a>.

// 2. 自定義屬性:新窗口打開 + nofollow
$str = 'https://example.com/';
echo autolink($str, ['target' => '_blank', 'rel' => 'nofollow']);
// 輸出: <a href="https://example.com/" rel="external nofollow" target="_blank">https://example.com/</a>
?>

優缺點評估

優點缺點/局限
代碼極簡、無依賴、性能極佳正則無法完美處理所有邊界(括號嵌套、Unicode 域名、郵箱地址等)
支持自定義屬性擴展不處理純域名(example.com)或郵箱鏈接
保留原始 URL 文本可讀性極長 URL 可能撐破版面(需 CSS word-break: break-all)

生產環境建議

  • 簡單場景(評論、論坛帖子)直接用此函數足夠。
  • 複雜富文本編輯器輸出、郵件正文解析,建議用成熟庫:**HTMLPurifier** (安全過濾 + 鏈接轉換)、**League\CommonMark** (Markdown 渲染器自動鏈接化)。
  • XSS 防護:輸出前務必對用戶輸入做 htmlspecialchars(),再調用 autolink(),避免注入腳本標籤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved