Validate URL Using PHP Regex

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.

* 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})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
return preg_match($pattern, $url);

$result = validateURL('');
print $result;

Hope this helps!

Be Sociable, Share!

About Shi Chuan

I am a web developer.
This entry was posted in PHP Regex and tagged . Bookmark the permalink.

13 Responses to Validate URL Using PHP Regex

  1. m0dk1d says:

    thanks for this simple yet handy script!

  2. Ben Wallis says:

    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

  3. admin says:

    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. :)

  4. Not very useful says:


    This regex fails in so many ways

  5. admin says:

    Hi, thanks for point out the problems. It’s fixed now.

  6. desbest says:

    This code does not work. It’s outdated now

  7. desbest says:

    Your code can tell whether something is in a url format such as it beginning with http:// or 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

  8. desbest says:

    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.

  9. admin says:

    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:

  10. Marian Bucur says:

    Not working… :(

    It allows garbage urls…

  11. Hawyqpyc says:

    Best Site good looking freexnxx >:-]]

  12. Wawlaywa says:

    Thanks funny site

  13. Pingback: PHP URL Validation Functions |