PHP Make URLs into Hyperlinks

On some blogs when you type an url or email address (not a hyperlink with <a> tags), it gets made into a link automatically. Here is a bit of code that does just that using regexp:

function add_html_links($string) 
{  
 //Make links beginning with 'ftp://' or 'http://'
 $string = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="\1">\1</a>', $string);  

 //Make links beginning with 'www.'
 $string = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '\1<a href="http://\2">\2</a>', $string);

 //Make mailto: links out of text that is in email format
 $string = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', '<a href="mailto:\1">\1</a>', $string);   

 return $string;
}

Enjoy :)



2 comments:

  1. Thank you! This was just what I was looking for!

    ReplyDelete
  2. Use preg_replace against eregi_replace because of it's a deprecated function

    ReplyDelete