在評論、論壇、即時通訊等用戶生成內容(UGC)場景中,自動將純文本 URL、郵箱、FTP 地址轉為 HTML 鏈接是基礎需求。本文提供 text2links() 函數,支援 http/https/ftp/www/郵箱多協議識別。
function text2links($str = '') {
if ($str === '' || !preg_match('/(http|www\.|@)/i', $str)) {
return $str;
}
$lines = explode("\n", $str);
$new_text = '';
foreach ($lines as $line) {
// 補全協議頭
$line = preg_replace("/([ \t]|^)www\./i", "\\1https://www.", $line);
$line = preg_replace("/([ \t]|^)ftp\./i", "\\1ftp://ftp.", $line);
// URL 轉鏈接
$line = preg_replace("/(http:\/\/[^ )\r\n!]+)/i", '\\1', $line);
$line = preg_replace("/(https:\/\/[^ )\r\n!]+)/i", '\\1', $line);
$line = preg_replace("/(ftp:\/\/[^ )\r\n!]+)/i", '\\1', $line);
// 郵箱轉 mailto
$line = preg_replace(
"/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/i",
'\\1',
$line
);
$new_text .= $line . "\n";
}
return $new_text;
}
$text = "Welcome www.jb51.net :-) Check https://example.com and email me@domain.com"; echo text2links($text); /* 輸出: Welcome https://www.jb51.net :-) Check https://example.com and me@domain.com */
([ \t]|^)www\.:行首或空白後的 www.,補全 https://。(http:\/\/[^ )\r\n!]+):匹配非空白、非標點結尾的 HTTP URL。htmlspecialchars(),或使用 filter_var($url, FILTER_VALIDATE_URL) 白名單驗證。rel="nofollow noopener noreferrer" 防止權重傳遞與標籤頁劫持。example.com/very/long/...),保持 UI 整潔。將此函數集成至模板引擎過濾器(如 Twig |autolink、Laravel Blade 指令),即可全站生效。