Replace URLs in text with HTML links

后端 未结 17 2107
栀梦
栀梦 2020-11-22 11:27

Here is a design though: For example is I put a link such as

http://example.com

in textarea. How do I get PHP t

17条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 11:50

    I've been using this function, it works for me

    function AutoLinkUrls($str,$popup = FALSE){
        if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)){
            $pop = ($popup == TRUE) ? " target=\"_blank\" " : "";
            for ($i = 0; $i < count($matches['0']); $i++){
                $period = '';
                if (preg_match("|\.$|", $matches['6'][$i])){
                    $period = '.';
                    $matches['6'][$i] = substr($matches['6'][$i], 0, -1);
                }
                $str = str_replace($matches['0'][$i],
                        $matches['1'][$i].'http'.
                        $matches['4'][$i].'://'.
                        $matches['5'][$i].
                        $matches['6'][$i].''.
                        $period, $str);
            }//end for
        }//end if
        return $str;
    }//end AutoLinkUrls
    

    All credits goes to - http://snipplr.com/view/68586/

    Enjoy!

提交回复
热议问题