Skip to content

Instantly share code, notes, and snippets.

@YohannParis
Last active December 13, 2015 18:28
Show Gist options
  • Save YohannParis/4955652 to your computer and use it in GitHub Desktop.
Save YohannParis/4955652 to your computer and use it in GitHub Desktop.
Validate URL in PHP with RegExp.
<?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