Tuesday, 24 January 2012

Converting text with links in anchored html

Many a times developer need functions to auto convert text links into the anchored url. Here is a small effort to do quickly.
function _make_url_href($matches) {
 $ret = '';
 $url = $matches[2];
 
 if ( empty($url) )
  return $matches[0];
 // removed trailing [.,;:] from URL
 if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
  $ret = substr($url, -1);
  $url = substr($url, 0, strlen($url)-1);
 }
 return $matches[1] . "$url" . $ret;
}
 
function _make_web_ftp_href($matches) {
 $ret = '';
 $dest = $matches[2];
 $dest = 'http://' . $dest;
 
 if ( empty($dest) )
  return $matches[0];
 // removed trailing [,;:] from URL
 if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
  $ret = substr($dest, -1);
  $dest = substr($dest, 0, strlen($dest)-1);
 }
 return $matches[1] . "$dest" . $ret;
}
 
function _make_email_href($matches) {
 $email = $matches[2] . '@' . $matches[3];
 return $matches[1] . "$email";
}
 
function make_href($ret) {
 $ret = ' ' . $ret;
 // in testing, using arrays here was found to be faster
 $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_href', $ret);
 $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_href', $ret);
 $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_href', $ret);
 
 // this one is not in an array because we need it to run last, for cleanup of accidental links within links
 $ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3
", $ret);
$ret = trim($ret);
return $ret;
}


$str = 'Here is some text with links such as http://www.youtube.com , www.google.com and admin@example.com. Here is the text html.';

echo make_href($str);

No comments :

Post a Comment