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