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

by Yang Yang on March 4, 2010

Share This Article:
Subscribe to Kavoir: blog feed

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.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 3 comments… read them below or add one }

MySQL programmer June 23, 2010 at 4:29 pm

This is a nice example. Its easy to understand..
doing a good job.
Thanks a lot..!

Reply

Dan Gayle August 6, 2010 at 7:20 am

I love the filter_var function for validation, EXCEPT for this one fact:
The FILTER_VALIDATE_URL filter has a bug in it that fails url hostnames with hyphens in them, as of 5.2.13. That sucks!

Reply

Yeahhhhh June 13, 2011 at 1:43 am

if (filter_var($url, FILTER_VALIDATE_URL) !== false)

==> if (filter_var($url, FILTER_VALIDATE_URL))

it’s the same !!!!
and more understandable

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: