tags:

views:

209

answers:

3

I am validating URL using ereg method. Here is my code:

function validationURL($URL) {
    if (ereg("^(http://www|www)[.]([a-z,A-Z,0-9]+)([-,_])([a-z,A-Z,0-9]+)[.]([a-z,A-Z]){2,3}[.]?(([a-z,A-Z]){2,3})[/]?[~]?([/,a-z,A-Z,0-9]+)?$",$URL)){
        return true;
    } else {
        return false;
    }
}


if ($website !="" && $website !=NULL) {
    if (validationURL($website)){
        $websiteOk = true;
    } else {
        $errmsg = $errmsg . "URL Is Invalid.<br>";
        $websiteOk = false;
    }
}

Any one can tell me whats wrong with this code. I tested www.google.com.my but its not working.

+2  A: 

I'm not the best with regex, but have you looked into PHP built in filters [The filter extension is enabled by default as of PHP 5.2.0.]?

There is a URL filter: http://us.php.net/manual/en/filter.filters.validate.php

specific URL filter example: http://www.phpro.org/tutorials/Filtering-Data-with-PHP.html#8

easement
+5  A: 

Not an answer to your question maybe, but you do know there's a better way to do this since of PHP5? The function is called filter_var and you can use it to validate URL's and email-addresses among other things. Example:

$website = $_POST['postedInAForm_Maybe'];
if (filter_var($website, FILTER_VALIDATE_URL)) {
    echo "Yay!";
} else {
    echo "Nah.";
}

You can find the filters here.

Björn
A: 

I agree with Björn, but if you cannot use filter_var, then it's always better to use the preg functions (Perl-Compatible Regular Expressions), as the ereg (POSIX) functions are now depreciated.

This blog post has some really good REGEX examples.

Rowan