Find URLs in Text, Make Links

The basic function of this is to find any URLs in the block of text and turn them into hyperlinks. It will only find URLs if they are properly formatted, meaning they have a http, https, ftp or ftps.
<?php

function autolink($str, $attributes=array()) {
$attrs = '';
foreach ($attributes as $attribute => $value) {
$attrs .= " {$attribute}="{$value}"";
}

$str = ' ' . $str;
$str = preg_replace(
'`([^"='>])((http|https|ftp)://[^s<]+[^s<.)])`i',
'$1<a href="$2"'.$attrs.'>$2</a>',
$str
);
$str = substr($str, 1);

return $str;
}

?>


Syntaxe



string autolink ( string $str [, array $attributes = array() ] )


Arguments



  1. str - La chaîne d'entrée.

  2. attributes - Optionnel. Si spécifié, ce paramètre doit être un tableau associatif de format $arr['attribute'] = $value.



Valeurs de retour



Retourne une copie de la chaîne str dont les urls ont été encapsulées dans des balises <a>.


Exemples



Exemple #1 Exemple avec autolink()






<?php










$str 'A link : http://example.com/?param=value#anchor.';





$str = autolink($str);










echo $str// A link : <a href="http://example.com/?param=value#anchor">http://example.com/?param=value#anchor</a>.










?>





Exemple #2 Exemple avec autolink()






<?php










$str 'http://example.com/';





$str = autolink($strarray("target"=>"_blank","rel"=>"nofollow"));










echo $str// <a href="http://example.com/" target="_blank" rel="nofollow">http://example.com/</a>










?>




Extract URL contentwith PHP and jQuery like Facebook

Embed instant messaging into your Web App!