From Superk
/**
* htmlTools::insertLinks - Function for converting in-line URL's to hyperlinks
*
* This function automatically parses text strings for URL's and turns them
* into clickable HTML hyperlinks.
*
* Example Usage:
* <code>
* $html = new htmlTools;
* $text = "Email jdoe@someplace.com or go to www.someplace.com.";
* $output = $html->insertLinks($text);
* echo $output;
* </code>
*
* This example produces:
* <code>
* $output = "Email <a href="mailto:jdoe@someplace.com">jdoe@someplace.com</a> or
* go to <a href="http:\/\/www.someplace.com">http:\/\/someplace.com</a>."
* </code>
*
* @param string $str Input text to parse
* @return string Parsed text with HTML encoded hyperlinks
* @see removeLinks
* @author Benjamin Krein <bkrein@desertmuseum.org>
*/
function insertLinks($str) {
// First match things beginning with http:// (or other protocols)
$NotAnchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)';
$Protocol = '(http|ftp|https):\/\/';
$Domain = '([\w]+.)?([\w]+)';
$Subdir = '([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?';
$Expr = '/' . $NotAnchor . $Protocol . $Domain . $Subdir . '/i';
$Result = preg_replace( $Expr, "<a href=\"$0\" title=\"$1\" target=\"_blank\">$0</a>", $str );
// Now match things beginning with www.
$NotAnchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)';
$NotHTTP = '(?<!:\/\/)';
$Domain = 'www(\.[\w]+)';
$Subdir = '([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?';
$Expr = '/' . $NotAnchor . $NotHTTP . $Domain . $Subdir . '/i';
$Result = preg_replace( $Expr, "<a href=\"http://$0\" title=\"http://$0\" target=\"_blank\">$0</a>", $Result );
$NotAnchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)';
$who = '\w+@';
$Subdir = '([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?';
$Expr = '/' . $NotAnchor . $who . $Subdir . '/i';
return preg_replace( $Expr, "<a href=\"mailto:$0\" title=\"mailto:$0\" target=\"_blank\">$0</a>", $Result );
}