Replace URLs with links - PHP


/ Published in: PHP
Save to your folder(s)

A really handy snippet that will replace textual URLs with HTML links.

Also works for email addresses.


Copy this code and paste it in your HTML
  1. function replace_links( $text )
  2. {
  3. $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
  4.  
  5. $ret = ' ' . $text;
  6.  
  7. // Replace Links with http://
  8. $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
  9.  
  10. // Replace Links without http://
  11. $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
  12.  
  13. // Replace Email Addresses
  14. $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
  15. $ret = substr($ret, 1);
  16.  
  17. return $ret;
  18. }

URL: http://www.apashley.co.uk/snippets/40/Replace-Urls-With-Links--Php.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.