将文本中的所有 URL 替换为 PHP 中的可点击链接


Replace all URLs in text to clickable links in PHP

我有一个用PHP编写的Web应用程序。我想在用户评论中找到所有 URL,并将它们更改为可点击的链接。我搜索了许多网站和页面,并在下面找到了解决方案(不幸的是,我没有再次找到它的参考链接):

<?php
function convert($input) {
   $pattern = '@(http)?(s)?(://)?(([a-zA-Z])([-'w]+'.)+([^'s'.]+[^'s]*)+[^,.'s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$4">$0</a>', $input);
}
?>

由于它的作者,这段代码完美运行。但是我发现其中有一个我无法解决的错误。
如果检测到的 URL 以 s 字母开头(不带 https),则 href 值将不包含该 s 字符,http 将更改为 https,而内部文本是正确的。

例:
source.com>> <a href="https://ource.com">source.com</a>

您有任何解决方案来解决此错误吗?

function convert($input) {
   $pattern = '@(http(s)?://)?(([a-zA-Z])([-'w]+'.)+([^'s'.]+[^'s]*)+[^,.'s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
}

演示

function convert($input) {
   $pattern = '@(http(s)?://)?(([a-zA-Z0-9])([-'w]+'.)+([^'s'.]+[^'s]*)+[^,.'s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
}

这是@splash58伙计答案的更新,用于处理以数字而不是字母开头的 URL。示例是 11hub.net 或 9gag.com

谢谢 splash58 的精彩回答!

$pattern = '@(http(s)?://)?(([a-zA-Z0-9])([-'w]+'.)+([^'s'.<]+[^'s<]*)+[^,.'s<])@';

这是@splash58答案和@Gero尼科洛夫答案的更新。如果文本以<字符结尾,则会出现错误。>

例:

<p>some text https://example.com</p>

结果:

<p>some text <a href="https://example.com</p>">https://example.com</p></a>

使用指定的模式,结果将是正确的。