PHP Function Check or Validate URL and Email Addresses – an Easier Way than Regular Expressions, the filter_var() Function-R&D26012012

To check if a URL or an email address is valid, the common solution is regular expressions. For instance, to validate an email address in PHP, I would use:

if (preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email)) {
    // $email is valid
}

A simpler and more forgiving one would be:

|^\S+@\S+\.\S+$|

Which is usually quite enough for signup forms in preventing stupid typo errors. You get to validate the email by a validation link sent to the address anyway, as a final call whether the address is valid or not. For those who are obsessively curious, this may serve you well.

For URL, you can use this one:

|^\S+://\S+\.\S+.+$|

Or you can use one that is insanely detailed in addressing what a valid URL should be.
The filter_var() function of PHP5

What we are talking about here really is the filter_var() function of PHP5 that simplifies the URL and email validation by a large degree. To validate an email:

if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
    // $email contains a valid email
}

To validate a URL:

if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
    // $url contains a valid URL
}

While filter_var() is meant to return the filtered results of the input according to the filter type specified, such as FILTER_VALIDATE_EMAIL or FILTER_VALIDATE_URL, you can generally use it to see if a valid email or a valid URL can be extracted from something. Better yet, filter and get the results first, use the result if it is good or abandon it when it is false:

$filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($filtered_email !== false) {
    // $filtered_email is the valid email got out of $email
} else {
    // nothing valid can be found in $email
}

Same applies to FILTER_VALIDATE_URL. Here’s a full list of filter types of filter_var() you can take advantage of.