Last active
December 13, 2015 18:28
-
-
Save YohannParis/4955652 to your computer and use it in GitHub Desktop.
Validate URL in PHP with RegExp.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* === URL validation | |
* [scheme] hostname [path] [file[getquery]] [#anchor] | |
* http://example.com/test/user.php?id=1234#details | |
*/ | |
function validURL($url){ | |
/* --- Scheme | |
* http://, https:// or nothing. | |
*/ | |
$regexURL = '((https?)\:\/\/)?'; | |
/* --- Hostname | |
* domain and sub-domain with a minimum of 2 characters. | |
* top-domain 2 or 3 characters. | |
* example.com, example.ca, example.gov.ca, shop.example.com, test-site.example.com, etc. | |
*/ | |
$regexURL .= '(\w{2,}\.)+[a-zA-Z]{2,3}'; | |
/* --- Path | |
* folder path | |
* /, or /test, /test/, /test/awesome, /test/awesome/ | |
*/ | |
$regexURL .= '((\/[\w+-]+)*\/?)?'; | |
/* --- File | |
* - Check up the last element of the file if it's a file. | |
* file.extension | |
* - GET query | |
* ?user=123&name=Yohann%20Paris&class=test::cool | |
*/ | |
$regexURL .= '([\w-]+\.\w{2,}(\?[\w+\&\$-][\w;:@\&%=+\$-]*)?)?'; | |
/* --- Anchor | |
* #, #title, #cool-Title | |
*/ | |
$regexURL .= '(#[\w-]*)?'; | |
/* --- Validate the entirely URL */ | |
$regexURL = '/^'.$regexURL.'$/'; | |
return preg_match($regexURL, $url); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment