开发者

How do I auto convert an url into a hyper link in PHP?

开发者 https://www.devze.com 2023-02-21 14:45 出处:网络
I have a script that outputs status updates and I need to write a script that automatically changes something like www.example.com into a hyper link in a chunk of text like Twitter and Facebook do. Wh

I have a script that outputs status updates and I need to write a script that automatically changes something like www.example.com into a hyper link in a chunk of text like Twitter and Facebook do. What functions can I use for this in PHP? If you know a tutorial please post i开发者_StackOverflow社区t.


$string = " fasfasd  http://webarto.com   fasfsafa";

echo preg_replace("#http://([\S]+?)#Uis", '<a rel="nofollow" href="http://\\1">\\1</a>', $string);

Output:

 fasfasd  <a rel="nofollow" href="http://webarto.com">webarto.com</a>   fasfsafa


You can use a regex to replace the url with a link. Look at the answers on this thread: PHP - Add link to a URL in a string.


Great solution!

I wanted to auto-link web links and also to truncate the displayed URL text, because long URLs were breaking out of the layout on some platforms.

After much fiddling around with regex, I realised the solution is actually CSS - this site gives a simple solution using CSS white-space.


Here is the working Function

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].'</xmp><a href="http'.
                $matches['4'][$i].'://'.
                $matches['5'][$i].
                $matches['6'][$i].'"'.$pop.'>http'.
                $matches['4'][$i].'://'.
                $matches['5'][$i].
                $matches['6'][$i].'</a><xmp>'.
                $period, $str);
    }//end for
}//end if
return $str; }
0

精彩评论

暂无评论...
验证码 换一张
取 消