tags:

views:

146

answers:

2

Is there a regex out there that can find a string that contains a word that starts with either http:// or www and wrap it with <a>$1</a>?

Been googling but I can't seem to find a ultimate one.

Another question, Could you somehow make it ignore it if its inside a <img> tag ?

Thanks a bunch!

+2  A: 
    $text = trim($text);
    while ($text != stripslashes($text)) { $text = stripslashes($text); }    
    $text = strip_tags($text,"<b><i><u>");
    $text = preg_replace("/(?<!http:\/\/)www\./","http://www.",$text);
    $text = preg_replace( "/((http|ftp)+(s)?:\/\/[^<>\s]+)/i", "<a href=\"\\0\" target=\"_blank\">\\0</a>",$text);
Devin Ceartas
a snippet from a function I use often; also contains (not shown) code to replace email with links, optionally obfuscated
Devin Ceartas
works like a charm! thank you very much
A: 

Good luck with this one — finding the beginning is fairly easy (most of the time); finding the end? Good luck:

  • http://example.com/bob.jones.4.
  • http://example.com/bob.jones.4?
  • http://example.com/bob.jones.4!
  • http://stackoverflow.com/questions/1242733/make-links(oh-noes)
  • http://example.com/bob.'magic'.jones*2!
  • http://example.com/~(*)!

Those are valid URLs. See RFC2396. But sometimes you want the trailing punctuation, sometimes you don't.

/me wonders what he can use a url with (*')! in it for, now that he knows its permitted by RFC2396.

derobert