/ Published in: PHP
A source to help you interpreting URLs in plain text as a HTML link. It's an improvement of what was proposed here : http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/
Expand |
Embed | Plain Text
// Returns the text given as parameter, with contained URLs interpreted as HTML links return preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1">$1</a>', $text); }
Comments
Subscribe to comments
You need to login to post a comment.

Problem: This improperly matches the string "SearchCriteria: [email protected]"
thank you for your remark, I'll see what I can do and post a patch when found.
thank you for your remark, I'll see what I can do and post a patch when found.
Thank you very much. I have a problem: I need this matches the string http://www.terra.es. (look the final point at the end of the string). How can I not to include the last point? Sorry for mystakes.
To: tuxfede
I tried this with the trailing period e.g. mysite.org. and it worked perfectly.
BTW keevkilla; this is a very nice piece of work - I like the whole site.
John McKean - Toronto, Canada
What I wanted was a javascript snippet and keevkilla's was PHP. Backslashing the slashes satisfies JS and this snippet works (for me). However, it does capture punctuation that follows an html append.
function clickify_links($text) { return $text.replace(/((https?:\/\/)?([-\w]+.[-\w.]+)+\w(:\d+)?(\/([-\w_.]*(\?\S+)?)?)*)/gim, ""+"$1"+""); }
As a test:
function test() { $text = "your-site,net http://yoursite.com. bb dd mysite.org! ..." $text = $text+"yoursite.com .yoursite.com! https://yoursite.com: yoursite.com? " $text = $text+"yoursite.subsite.com/dir/blurb.html?name=billy-jean.
Hmm - my last comment got hopelessly mangled. Please ignore it
it doesnt find query link like http://www.mysite.com/?test=test/ I.E. some long link with path, query or other character http://www.mysite.com/#test
Great improvement but when a user imputs a string like: www.mysite.com the link will be incorrect because in the link-tag you wont have http:// before your result. Therefor the url of the user shall try to redirect towards a page into your own site. Is their a way to solve this?
This is a simple solution for www domains $text= pregreplace('@((https?://)?([-\w]+.[-\w.]+)+\w(:\d+)?(/([-\w/.](\?\S+)?)?))@', '$1', $text); $text= str_replace("href=\"www.","href=\"http://www.",$text);
but when the user inserts a url like: mail.mysite.com it wont work. It wont even pass the preg_replace funtion.