0

I need to search through a string entered by a user and convert anything that is plain text and resembles a url into a url.

Im not concerned with how to construct the URL, more how to determine if the text is actually a url. I was thinking about a regular expression (see How to replace plain URLs with links?), but ideally would like a solution that is more readable.

I suppose I would need to search for instances of http or www and wrap the string up until the next space in an anchor tag.

Does anyone have any pointers, especially seen as urls can be so varied now a days?

EDIT:

A user enters text into an input that is submitted, when displayed on screen I need to check their comment for any possible links and convert them to a hyperlink.

Community
  • 1
  • 1
DavidB
  • 2,566
  • 3
  • 33
  • 63

1 Answers1

0

The first thing you need to do is look for anything that validated as an url. At what point do you want a url to be a url.

An valid url produces a result when entered in the browser addressbar produces a (desired) result ;

all of the above produce a result when typed in your browsers address bar. so if your tekst has any string that has no whitespace but has a dot ! its possible that its an url

(?<=[ ]).*?..+?(?=[ ])

will get your google.com out of

does google.com validated as an url

however determining if its a url can only be confirmed when you actually try to get the page.

The regex above will get you all 4 urls above, but also get you foobars. If you want to make sure you have a valid url, do a lookup of the page, if it turns 404 on you, it wasnt an url

Sedecimdies
  • 152
  • 1
  • 10
  • thanks, but ive got a good solution that will create a link out anythign starting https, http, ftp, www and will also create mailto links. Yours is a good suggestion but overkill I think for what I want – DavidB Oct 10 '13 at 08:35