在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.