一個 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) |
htmlspecialchars(),再調用 autolink(),避免注入腳本標籤。