May
17
Validate URL Using PHP Regex
May 17, 2008 |
There are times you may want a URL validation function that accepts (I think) most known types of URL’s. Useful for validating a homepage link, or submission of links from the public.
It allows for port, path and query string validations, the parameter $url string contains the user input URL and the function returns the boolean of true or false.
<?php
/**
* Validate URL
* Allows for port, path and query string validations
* @param string $url string containing url user input
* @return boolean Returns TRUE/FALSE
*/
function validateURL($url)
{
$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
return preg_match($pattern, $url);
}
$result = validateURL('http://www.google.com');
print $result;
?>
Hope this helps!
Similar Posts
- PHP Regex Validate IP address
- PHP Regex - Validate Email Address
- PHP Regex Remove Whitespace from HTML
- PHP Regex Extract Username from Email Address
- PHP Regex Extract Filename from Full Path
- PHP Regex Extract Directiory from Full Path
- PHP Regex - Extract Filenames from Full Path
Comments
12 Comments so far



































thanks for this simple yet handy script!
It doesn’t work for me in PHP 5.2.5
Warning: preg_match() [function.preg-match]: Unknown modifier ‘[’ in C:\xampp\htdocs\test.php on line 18
Hi, Ben
I have rewritten the code and tested it, now when you run the code above, you should get either ‘1′ or ‘0′ as results stands for ‘true’ or ‘false’.
Thanks for pointing it out. Do let me know if there is anymore problem. :)
http://www-google-com
http://www_google_com
This regex fails in so many ways
Hi, thanks for point out the problems. It’s fixed now.
This code does not work. It’s outdated now
Your code can tell whether something is in a url format such as it beginning with http:// or http://www. but it does not say whether a url actually exists.
i tried your code with a domain that does not exist and it said “1″ that the url was valid
After 10 minutes searching for a better url validator than this one, I couldn’t find one. I’ve added you to delicious.
Even the check if a url exist snippets dont work and require curl.
hi, desbest, mine script is a simple checker that may still need perfection. if there’s anything you can contribute to perfect it, i would appreciate it, i would try to perfect it if i got more time. maybe for now you can take a look at the following link which might be the thing you are looking for:
http://www.bootstrike.com/PHPAJAXDomainCheck/#bulkdomain
Not working… :(
It allows garbage urls…
Best Site good looking freexnxx >:-]]
Thanks funny site