I've been looking for a simple regex for URL's, does anybody have one handy that works well? I didn't find one with the zend framework validation classes and have seen several implementations.
Thanks
I've been looking for a simple regex for URL's, does anybody have one handy that works well? I didn't find one with the zend framework validation classes and have seen several implementations.
Thanks
As per the PHP manual - parse_url should not be used to validate a URL.
Unfortunately, it seems that
filter_var('example.com', FILTER_VALIDATE_URL)
does not perform any better.Both
parse_url()
andfilter_var()
will pass malformed URLs such ashttp://...
Therefore in this case - regex is the better method.
And there is your answer =) Try to break it, you can't!!!
For anyone developing with WordPress, just use
to validate a URL (here's WordPress' documentation on
esc_url_raw
). It handles URLs much better thanfilter_var($url, FILTER_VALIDATE_URL)
because it is unicode and XSS-safe. (Here is a good article mentioning all the problems withfilter_var
).I've found this to be the most useful for matching a URL..
Inspired in this .NET StackOverflow question and in this referenced article from that question there is this URI validator (URI means it validates both URL and URN).
I have successfully unit-tested this function inside a ValueObject I made named
Uri
and tested byUriTest
.UriTest.php (Contains valid and invalid cases for both URLs and URNs)
Uri.php (Value Object)
Running UnitTests
There are 65 assertions in 46 tests. Caution: there are 2 data-providers for valid and 2 more for invalid expressions. One is for URLs and the other for URNs. If you are using a version of PhpUnit of v5.6* or earlier then you need to join the two data providers into a single one.
Code coverage
There's is 100% of code-coverage in this sample URI checker.