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.
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".
:) | |
Cool! Will it work for the following types?
concordia University.url
How do you prevent it from fucking with working links? | |
It didn't work, but I should have known that. | |
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. | |
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. | |
Hey thanks, saved me a lot of time! | |
|
|