Posted By

plesh on 07/12/11


Tagged

regex php regular expressions


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

freaktheclown
tux-world


Replace URLs with links - PHP


 / Published in: PHP
 

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

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

Also works for email addresses.

  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. }

Report this snippet  

You need to login to post a comment.