Transform Text Links Into Anchors

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.

function createTextLinks($str = '') {
 
 if($str=='' or !preg_match('/(http|www\.|@)/im', $str)){
  return $str;
 }
 
 // replace links:
 $str = preg_replace("/([ \t]|^)www\./im", "\\1http://www.", $str);
 $str = preg_replace("/([ \t]|^)ftp\./im", "\\1ftp://ftp.", $str);
 
 $str = preg_replace("/(https?:\/\/[^ )\r\n!]+)/im", "<a href=\"\\1\" title=\"\\1\">\\1</a>", $str);
 
 $str = preg_replace("/(ftp:\/\/[^ )\r\n!]+)/im", "<a href=\"\\1\" title=\"\\1\">\\1</a>", $str);
 
 $str = preg_replace("/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/im", "<a href=\"mailto:\\1\" title=\"Email \\1\">\\1</a>", $str);
 
 $str = preg_replace("/(\&)/im","\\1amp;", $str);
 
 return $str;
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.