Transform Text Links Into Anchors

28th May 2008

Using the strip_tags() function on any user generated input should be common practice in order to stop users putting in odd bits of HTML and messing up your nicely coded HTML. You might want to allow anchor tags to be used, which is fine, but some users might use this to include onmouseover and other events in order to run JavaScript annoyances on the page.

So after stripping all tags from your text you can then run the following function to turn any links into anchor elements. This will work with any plain text that you want to use it on.

  1. function createTextLinks($str='')
  2. {
  3.  
  4. if($str=='' or !preg_match('/(http|www\.|@)/im', $str)){
  5. return $str;
  6. }
  7.  
  8. // replace links:
  9. $str = preg_replace("/([ \t]|^)www\./im", "\\1http://www.", $str);
  10. $str = preg_replace("/([ \t]|^)ftp\./im", "\\1ftp://ftp.", $str);
  11.  
  12. $str = preg_replace("/(https?:\/\/[^ )\r\n!]+)/im", "\\1", $str);
  13.  
  14. $str = preg_replace("/(ftp:\/\/[^ )\r\n!]+)/im", "\\1", $str);
  15.  
  16. $str = preg_replace("/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/im", "\\1", $str);
  17.  
  18. $str = preg_replace("/(\&)/im","\\1amp;", $str);
  19.  
  20. return $str;
  21. }

Add new comment

The content of this field is kept private and will not be shown publicly.