a PHP or PERL regular expression to make links out of URLs

I just spent the last little while writing this virtuously verbose line of code. It does a search and replace using PERL regular expression syntax from PHP. (Note that the line breaks should be removed for it to work):
$post = preg_replace('/(?mi)([^"\'])((http|ftp):\/\/
([_a-zA-z0-9\-]+\.)+[_a-zA-z0-9\-]{2,5}(\/[_a-zA-z0-
9\-\.~]*)*(\?[_a-zA-z0-9\-\.~&=;]*)?)/', '\1"\2">\2', " ".$post );
It's effect it to turn a fully qualified URL (i.e. something that starts with http://) into a link. For example http://test.com. It has to be so complex because there is a large variety in what URLs look like. For example ftp://somethinglong.foo.co.nz/blah-goo/~filter.shtml?t&a=good is a perfectly valid URL and should therefore be linked as one. Feel free to try and stump it by giving some wacked out URLs.

It will work in comments as well.

Posted by dustin on January 20, 2004 with category tags of

6 comments
I feel like this effort is my fault since I'm to lazy to a href it when I post my "Stupid Link Of The Day".

:)
   comment by vinny9 (#33) on January 21, 2004

Cool! Will it work for the following types?

concordia University.url

How do you prevent it from fucking with working links?
   comment by Mariana on January 21, 2004

It didn't work, but I should have known that.
   comment by Mariana on January 21, 2004

The [^"\'] part at the beginning prevents it from fucking up working links. That means anything except for a single or double quote. Since properly linked URLs must have a quote right before the http they don't get picked up.
   comment by dustin (#1) on January 21, 2004

I didn't test it, but it looks to me like it doesn't support specifying a port, e.g. "http://www.google.com:80/", which is perfectly valid.

Also, it doesn't support https. Try changing the "(http|ftp)" to "(https?|ftp)". Or failing that, "(http|https|ftp)" would work just as well, I guess.
   comment by Lee K. Seitz on January 13, 2005

Hey thanks, saved me a lot of time!
   comment by marcus on July 19, 2005

   

VorgTag Cloud

Written by dustin
Latest Photo
Quote of Now:
Friends
Popular Posts
Computer Games

Hey You! Subscribe to dustin's RSS feed.
Or get wider opinion in the Vorg All Author feed.

 
 

Members login here.
© Vorg Group.