且构网

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

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

更新时间:2023-01-23 09:19:48

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

Here is another 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;

下面的脚本将捕获所有 URL 类型并将它们转换为可点击的链接.

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 指出这一点.

The 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;

这里有一个非常简单的解决 URL 显示不正确的方法.

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.

我提供了多个答案,因为有些服务器的设置不同,所以一个答案可能适用于某些人,但不适用于其他人,但我希望答案对您有用,如果没有,请告诉我,希望,我可以想出另一个解决方案.

I've provided multiple answers as some servers are set up differently, so one answer may work for some but not for others, but I hope the answer(s) work for you and if not then let me know, and hopefully, I can come up with another solution.

有多个脚本,因为有些 PHP 文件需要不同的脚本,有些服务器的设置也不同,而且每个都有不同的要求,有些只需要 HTTP/S,有些需要 WWW,有些需要 FTP/S,每个都可以工作关于如何设置用户自己的脚本,我为每个人提供了一些文字说明他们的工作.

There are multiple scripts as some PHP files require different scripts also some servers are set up differently, Plus each has different requirements, Some want just HTTP/S, some want WWW and some want FTP/S, Each one will work depending on how the users own scripts are set up, I provided some text with each one with what they do.