/ Published in: PHP
This regular expression matches a URL.
Expand |
Embed | Plain Text
https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)? $text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
Comments
Subscribe to comments
You need to login to post a comment.

Exactly what I needed. I heart you.
Perfect. Thank you!
Perfect for copy-and-paste. Very nice regex, thank you! -cej102937
Great regex, thanks ! Small thing : the '-' (dash) is missing - URL like this fails (http://web5.uottawa.ca/admingov/reglements-methodes.html)
Great regex, thanks ! Small thing : the '-' (dash) is missing - URL like this fails (http://web5.uottawa.ca/admingov/reglements-methodes.html)
it's also missing left parenthesis, right parenthesis, and comma.
Perfect! I spent the better part of this morning looking for a great URL matching snippet and finally found it here. Thank you!
Took me a few min to track this down on Google but it was exactly what I was looking for. Thank You.
Does this work with links that do not have the "http" or "https" in front of it. like ubuntu.com for example?
I improved the regex given here, to take into account your comments : pregreplace('@((https?://)?(\w+.[-\w.]+)+\w(:\d+)?(/([-\w/.](\?\S+)?)?))@', '$1', $text);
Now with this regex, the links can be without any http:// or https:// block (like www.exemple.com) and can have multiple /folder/subfolder/file.htm after the domain, and finally "-" are considered as part as a standard URL.
Thanks for the first regex that helped me a lot find this one ! I hope mine will help the others.
just replace the regex by '@((https?://)?(\w+.[-\w.]+)+\w(:\d+)?(/(-\w/.?)?))@' because in my last post, some characters are missing because of misinterpretation...
Well it also removes the underscores... So I posted my contribution here : http://snipplr.com/view/36991/improvement-of-url-interpretation-with-regex/
Last (but not least) change of snippet location : http://snipplr.com/view/36992/improvement-of-url-interpretation-with-regex/