且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中将纯文本URL转换为HTML超链接

更新时间:2023-01-23 09:58:47

这是另一个解决方案,这将捕获所有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.