PHP URL Validate using RegEx

This item was filled under [ PHP ]

After going through lots and lots of url validation scripts, I come across this wonderful and easy RegEx validation script works perfectly. This information has been posted in phpcentral by fqa. Amazingly author has also given detailed information for switching how a URL should be. For example, http://localhost is a VALID URL and you may want to allow this as valid url. Maybe you want to validate http://www.bloodyerror.com as VALID URL and http://localhost as INVALID URL.

// SCHEME
$urlregex = "^(https?|ftp)\:\/\/";

// USER AND PASS (optional)
$urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";

// HOSTNAME OR IP
$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // http://x = allowed (ex. http://localhost, http://routerlogin)
//$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+";  // http://x.x = minimum
//$urlregex .= "([a-z0-9+\$_-]+\.)*[a-z0-9+\$_-]{2,3}";  // http://x.xx(x) = minimum
//use only one of the above

// PORT (optional)
$urlregex .= "(\:[0-9]{2,5})?";
// PATH  (optional)
$urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
// GET Query (optional)
$urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?";
// ANCHOR (optional)
$urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?\$";

// check
if (eregi($urlregex, $url)) {echo "good";} else {echo "bad";}

It worked just the way I wanted and it saved me a lot of time figuring out how to write RegEx (It’s a Big Mess). Hope this help you too…

Source: http://www.phpcentral.com/208-url-validation-php.html

Tagged with: [ , , , ]
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment