Regex functino to validate a URL
-11
This is a faily simple function to validate a URL being passed into your scripts. It will allow for http, https, and ftp. The beginning www. of a URL is optional as well. It will also validate if you have an IP address in place of the domain name. I'm sure this can be improved upon as this is my first attempt at regular expressions but it has worked good for me so far. Please comment or improve if your able.
Thanks!
Thanks!
<?php
function isValidURL($URL)
{
return ereg("^((http|https|ftp)://)?(((www\.)?[^ ]+\.[com|org|net|edu|gov|us])|([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+))([^ ]+)?$", $URL);
}
?>
<?php
$url = array();
$url[0] = "www.pinellascounty.org/park/01_Anderson.htm";
$url[1] = "http://www.440WestCondominiums.com";
$url[2] = "https://136.174.187.14/bcc/reef/treasure_island_reef.htm";
$url[3] = "www.ci.gulfport.fl.us/history.htm";
$url[4] = "www.ci.gulfport.fl.us/City_Departments/Leisure_Services/Casino/Casino.htm";
$url[5] = "umUxiKeZOfP1BHL6fYEZnXEqaNvC7ijpJ1cr94ENZTDZZMV4iZRKwV0LgjLcIsH";
$url[6] = "ftp://rspdesign.net/";
foreach ($url as $k => $v)
{
if(isValidURL($v))
{
echo "URL is question: " . $v . "<br />";
echo "URL is <span style=\"font-weight: bold; color: blue; \">valid!</span><br /><br />";
}
else
{
echo "URL is question: " . $v . "<br />";
echo "URL is <span style=\"font-weight: bold; color: red; \">invalid!</span><br /><br />";
}
}
?>






One example that would not work with yours is ...
http://www.google.de/
or any other URL from a country TLD.
Here is a more inclusive test:
function isValidUrl($Url) {
//check for an empty url first
if (empty($Url)) { return false; }
//let php tell us if it as a valid url
$UrlElements = parse_url($Url);
if( (empty($UrlElements)) or (!$UrlElements) ) { return false; }
$scheme = $UrlElements[scheme];
$HostName = $UrlElements[host];
//check to make sure it has a scheme and hostname
if(empty($scheme) or empty($HostName)) { return false; }
//check the scheme (removes mailto and others)
if (!eregi("^(ht|f)tp",$scheme)) { return false; }
return true;
}