Linkify PHP text

心已入冬 提交于 2019-12-02 09:01:00

This is working well on the sites I am using it for...

function find_urls($t){
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    // Check if there is a url in the text
    if(preg_match($reg_exUrl, $t, $url)) {
        $add='';
        if (substr($url[0],(strlen($url[0])-1),strlen($url[0]))==")"){
            $url[0]=substr($url[0],0,(strlen($url[0])-1));
            $add=')';
        } else if (substr($url[0],(strlen($url[0])-1),strlen($url[0]))=="]"){
            $url[0]=substr($url[0],0,(strlen($url[0])-1));
            $add=']';
        }
        // make the urls hyper links
        return preg_replace($reg_exUrl, '<a href="'.$url[0].'">'.$url[0].'</a>'.$add, $t);
    } else {
        // if no urls in the text just return the text
        return $t;
    }
}

This is the only one i found that worked with www.

function link_it($text)
{
    $text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a     href=\"$3\" >$3</a>", $text);
    $text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text);
    $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text);
    return($text);
}

Hopefully this will help someone else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!