How TheUsual does it ...
/*
* urlactivate( $txt, &$found, $reg_exUrl )
* surround urls in txt with href or img html code
*/
function urlactivate (
$text,
&$found,
$reg_exUrl="/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"
) {
// PREPEND https:// TO BARE www.
$text = preg_replace( "#(?<!://)www.#", "https://www.", $text);
preg_match_all( $reg_exUrl, $text, $matches );
$usedUrls = array();
foreach( $matches[0] as $url ) {
if( !array_key_exists( $url, $usedUrls ) ) {
$found = TRUE;
$usedUrls[$url] = true;
if( isImage($url) ) {
$text = str_replace( $url, '<img src="'.$url.'">', $text );
}
else {
$offset=0;
while( ($p=stripos($text,$url,$offset)) !== FALSE ) {
$s = strtolower( substr($text,$p-9,9) );
if( $s != "<a href='" && $s != '<a href="' ) {
$text = substr_replace( $text,
'<a target=\"_blank\" href="'.$url.'">'.$url.'</a>',
$p,
strlen($url)
);
$offset += $p + ( 2 * strlen($url) ) + 14;
}
else $offset += $p + strlen($url);
if( $offset >= strlen($txt) ) break;
}
$text = str_replace( "<a href=", "<a target='_blank' href=", $text );
}
}
}
return $text;
}
function isImage( $url ) {
return stripos( "|.gif|.jpg|.png|.tif|.bmp|.ico|", substr($url,-4) )
|| stripos( "|.jpeg|.tiff|", substr($url,-5) );
}