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

2022-01-01 00:00:00 regex hyperlink php preg-replace

我有一个简单的评论系统,人们可以在其中提交纯文本字段内的超链接.当我将这些记录从数据库返回到网页中时,我可以使用 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 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.

相关文章