Regex functino to validate a URL





-11
Date Submitted Thu. Sep. 28th, 2006 3:43 PM
Revision 1 of 1
Helper ffxfiend
Tags "php" | PHP | phpcode | RegExp
Comments 1 comments
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!

<?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 />";
        }

}
 
?>

 

Jeremiah Poisson

rspdesign.net
*** Stay sane inside insanity ***

Comments

Comments Works for most URLs
Mon. Oct. 2nd, 2006 9:29 AM    Scripter ctiggerf

Voting