2

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 it.

Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
Joshua Davis
  • 325
  • 7
  • 15

4 Answers4

8
$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
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
0

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.

j0k
  • 22,600
  • 28
  • 79
  • 90
  • You shouldn't just give a link to another site as an answer, since the site may go out of date in the future. Instead, click the "edit" link on this answer and include the essential parts of the solution from that page here. See: http://meta.stackexchange.com/q/8259 – Peter O. Oct 19 '12 at 22:17
0

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; }
Ishaq Hassan
  • 135
  • 3
  • 9
0

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.

Community
  • 1
  • 1