Pryztojny
Pryztojny

Reputation:

Make links clickable with regex

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!

Upvotes: 1

Views: 3762

Answers (2)

derobert
derobert

Reputation: 51157

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.

Upvotes: 1

Devin Ceartas
Devin Ceartas

Reputation: 4829

    $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);

Upvotes: 9

Related Questions