-2

Does anyone know an up to date regular expression for validating URLs? I found a few on Google but they all allowed junk URL's i.e (www.google_com) when testing.

My regular expression knowledge is not so vast, so I would hate to put something together that would fail under pressure.

Thanks.

drudge
  • 35,471
  • 7
  • 34
  • 45
Jamie Redmond
  • 91
  • 1
  • 2
  • 6
  • possible duplicate of [Is regex a good way to test a url](http://stackoverflow.com/questions/3408839/is-regex-a-good-way-to-test-a-url). See also: http://stackoverflow.com/questions/408405/easy-way-to-test-a-url-for-404-in-php – Matt Ball Oct 26 '10 at 20:11

2 Answers2

4

You can use the filter functions in PHP

$filtered = filter_var($url, FILTER_VALIDATE_URL);

http://uk3.php.net/manual/en/function.filter-var.php

Alex Rashkov
  • 9,833
  • 3
  • 32
  • 58
1

Not every problem should be answered with a regex.

http://php.net/manual/en/function.parse-url.php

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • 1
    Hm… Cite: "This function is ***not*** meant to validate the given URL, it only breaks it up into the above listed parts." ;-) – Tomalak Oct 26 '10 at 20:19
  • I haven't tested, but I think by "validate" they mean "check that there's an actual page there". If it's not a valid URL, I'd imagine the splitting algorithm would choke. – ceejayoz Oct 26 '10 at 20:29
  • @ceejayoz: That's of course nonsense. An URL can be valid without pointing to an existing resource. The function will not make an HTTP. – Tomalak Oct 27 '10 at 09:02