0

Possible Duplicate:
Regex to match URL

I wrote a regular expression to validate only the following URL patterns

  1. http://www.abc.com
  2. www.abc.com
  3. abc.com
  4. http.www.abc.com

Can anyone give me a regular expression?

There's some error in the regex I used to do it, can anyone fix it?

/^((http|http|HTTP|HTTP):\/\/+(www|WWW\.)?[A-Za-z0-9\-\.]{1,}\.[A-Za-z])|((www|WWW\.)?[A-    Za-z0-9\-\.]{1,}\.[A-Za-z])/i.test(value);
Community
  • 1
  • 1
not 0x12
  • 19,360
  • 22
  • 67
  • 133
  • What happens when you try it? – Jay Maynard K5ZC Nov 24 '11 at 15:28
  • it matched 1,2,3,4 that you mentioned(though I didn't test in javascript). There is an error I suppose, in that 4 shouldn't be matched. But you want it to match 4 it seems. Perhaps you found it didn't match one of those, then show the error. – barlop Nov 24 '11 at 15:30

2 Answers2

2

Try this expression:

^(http(?:s)?\:\/\/[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*\.[a-zA-Z]{2,6}(?:\/?|(?:\/[\w\-]+)*)(?:\/?|\/\w+\.[a-zA-Z]{2,4}(?:\?[\w]+\=[\w\-]+)?)?(?:\&[\w]+\=[\w\-]+)*)$
f0rza
  • 480
  • 3
  • 17
0

Try this:

$url = "http://something.com/";
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
    echo "Your url is ok.";
} else {
    echo "Wrong url.";
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162