简体   繁体   English

将文本中的所有 URL 替换为 PHP 中的可点击链接

[英]Replace all URLs in text to clickable links in PHP

I have a web application written with PHP.我有一个用 PHP 编写的 Web 应用程序。 I wanted to find all URLs inside users comments and change them to clickable links.我想找到用户评论中的所有 URL,并将它们更改为可点击的链接。 I searched many websites and pages and found the solution below (Unfortunately I did not find its reference link again):我搜索了很多网站和页面,找到了下面的解决方案(很遗憾我没有再次找到它的参考链接):

<?php
function convert($input) {
   $pattern = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$4">$0</a>', $input);
}
?>

This code works perfectly thanks to its author.多亏了它的作者,这段代码才能完美运行。 But I found out there is a bug in it that I could not solve.但我发现其中有一个我无法解决的错误。
If detected URL started with s letter (without https), the href value won't have that s character and http will change to https , whereas inner text is correct.如果检测到的 URL 以s字母开头(不带 https), href值不会有那个s字符, http将更改为https ,而内部文本是正确的。

Example:例子:
source.com >> <a href="https://ource.com">source.com</a> source.com >> <a href="https://ource.com">source.com</a>

Do you have any solution to solve this bug?您有解决此错误的任何解决方案吗?

function convert($input) {
   $pattern = '@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
}

demo 演示

function convert($input) {
   $pattern = '@(http(s)?://)?(([a-zA-Z0-9])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
   return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
}

This is an update of the @splash58 dude answer to handle the URL which starts with number instead of letter. 这是@ splash58 dude答案的更新,用于处理以数字而不是字母开头的URL。 Example is 11hub.net or 9gag.com 例如11hub.net或9gag.com

Thank you splash58 for the great answer! 谢谢您splash58的出色回答!

$pattern = '@(http(s)?://)?(([a-zA-Z0-9])([-\w]+\.)+([^\s\.<]+[^\s<]*)+[^,.\s<])@';

This is an update of the @splash58 answer and @Gero Nikolov answer.这是@splash58 答案和@Gero Nikolov 答案的更新。 If the text ends with the < character, an error occurs.如果文本以 < 字符结尾,则会发生错误。

Example:例子:

<p>some text https://example.com</p>

Result:结果:

<p>some text <a href="https://example.com</p>">https://example.com</p></a>

With the specified pattern, the result will be correct.使用指定的模式,结果将是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM