在文本中查找 URL 并将其转换为链接

Avatar of Chris Coyier
Chris Coyier
<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);

} else {

       // if no urls in the text just return the text
       echo $text;

}
?>

此函数的基本功能是在文本块中查找任何 URL 并将其转换为超链接。它仅在 URL 格式正确时才会查找 URL,这意味着它们必须具有 http、https、ftp 或 ftps。

查看下面的评论以获取更多解决方案。