1

I would like to detect if a URI is located in a string, properly sanitize it, and output it with the proper anchor tags.

ie, a user inputs:

Check out our profile on facebook!
https://facebook.com/ourprofile

and our twitter!
twitter.com/#!/ourprofile

and email us!
ourprofile@stack.com

Is there a way to determine that there are URIs located in the string, sanitize unsafe characters and properly output a safe anchor?

so the output would be:

Check out our profile on facebook!
<a href="https://www.facebook.com/ourprofile">https://www.facebook.com/ourprofile</a>

and our twitter!
<a href="http://www.twitter.com/#!/ourprofile">twitter.com/#!/ourprofile</a>

and email us!
<a href="mailto:ourprofile@stack.com">ourprofile@stack.com</a>

the ideas i had in mind were using preg_match and simple preg_replace for removing unsafe characters, but this has failed me and im just going in circles, i dont really know where to start for this, as im almost certain a blacklist approach such as that is not proper or secure.

JimmyBanks
  • 4,178
  • 8
  • 45
  • 72
  • 1
    Looks like you're looking for http://stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior – MrCode Apr 13 '12 at 16:54

1 Answers1

3

I found this at experts-exchange.com. Hope, it helps:

function make_links($text)
{
  return  preg_replace(
     array(
       '/(?(?=<a[^>]*>.+<\/a>)
             (?:<a[^>]*>.+<\/a>)
             |
             ([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+)
         )/iex',
       '/<a([^>]*)target="?[^"\']+"?/i',
       '/<a([^>]+)>/i',
       '/(^|\s)(www.[^<> \n\r]+)/iex',
       '/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)
       (\\.[A-Za-z0-9-]+)*)/iex'
       ),
     array(
       "stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\">\\2</a>\\3':'\\0'))",
       '<a\\1',
       '<a\\1 target="_blank">',
       "stripslashes((strlen('\\2')>0?'\\1<a href=\"http://\\2\">\\2</a>\\3':'\\0'))",
       "stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))"
       ),
       $text
   );
}
The_Fritz
  • 452
  • 3
  • 17