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

Replace all URLs in text to clickable links in PHP

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

<?php
function convert($input) {
   $pattern = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
   return $output = preg_replace($pattern, '<a href="http://">[=11=]</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://">[=10=]</a>', $input);
}

demo

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

这是对 @splash58 花花公子回答的更新,用于处理以数字而不是字母开头的 URL。例如 11hub.net 或 9gag.com

感谢 splash58 的精彩回答!

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

这是@splash58 回答和@Gero Nikolov 回答的更新。 如果文本以 < 字符结尾,则会发生错误。

示例:

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

结果:

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

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