在PHP中将纯文本URL转换为HTML超链接 [英] Convert plain text URLs into HTML hyperlinks in PHP

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

问题描述

我有一个简单的评论系统,人们可以在纯文本字段中提交超链接。当我从数据库和网页中显示这些记录时,我可以使用PHP中的RegExp将这些链接转换为HTML类型的锚链接吗?

I have a simple commenting system where people can submit hyperlinks inside the plain text field. When I display these records back from the database and into the web page, what RegExp in PHP can I use to convert these links into HTML-type anchor links?

我不喜欢不希望算法用任何其他类型的链接来做,只需要http和https。

I don't want the algorithm to do this with any other kind of link, just http and https.

推荐答案

这是另一个解决方案,这将捕获所有http / https / www并转换为可点击的链接。

Here is an other solution, This will catch all http/https/www and convert to clickable links.

$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; 
$string = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string);
echo $string;

或者只是为了捕获http / https,然后使用下面的代码。

Alternatively for just catching http/https then use the code below.

$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';   
$string= preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string);
echo $string;

编辑:
以下脚本将捕获所有网址类型并将其转换为可点击链接。

The script below will catch all url types and convert them to clickable links.

$url = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
$string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
echo $string;

新的更新,如果你有字符串条(s),那么使用下面的代码块,感谢@AndrewEllis指出这一点。

New update, If you're having the string strip the (s) then use the below code block, Thanks to @AndrewEllis for pointing this out.

$url = '@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
$string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
echo $string;

这是一个非常简单的解决方案,无法正确显示网址。

Here's a very simple solution for the URL not displaying correctly.

$email = '<a href="mailto:email@email.com">email@email.com</a>';
$string = $email;
echo $string;

这是一个非常简单的修复,但你必须为自己的目的修改它。

It is a very simple fix but you will have to modify it for your own purpose.

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

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