将文本中的所有 URL 替换为 PHP 中的可点击链接 [英] Replace all URLs in text to clickable links in PHP

查看:25
本文介绍了将文本中的所有 URL 替换为 PHP 中的可点击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a web application written with PHP. I wanted to find all URLs inside users comments and change them to clickable links. I searched many websites and pages and found the solution below (Unfortunately I did not find its reference link again):

<?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,而内部文本是正确的.

This code works perfectly thanks to its author. But I found out there is a bug in it that I could not solve.
If detected URL started with s letter (without https), the href value won't have that s character and http will change to https, whereas inner text is correct.

示例:
source.com >> source.com

您有解决此错误的解决方案吗?

Do you have any solution to solve this bug?

推荐答案

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);
}

演示

这篇关于将文本中的所有 URL 替换为 PHP 中的可点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆