Entry
How do I validate an Email Address using PHP3?
Jul 25th, 2005 04:04
J. Amgine Neilson, mike gifford,
The basic answer is to compare the e-mail address using a regular
expression, returning a boolean true if the e-mail address follows the
basic RFC requirements or a boolean false if it does not. The preg_match
function of PHP has been available since PHP 3.0.9
Here's a fairly strict regular expression which can be used:
$pattern = '/
^ # anchor at the beginning
[^@\s]+ # name is all characters, except @ and whitespace
@ # the @ divides the name and domain
(
[-a-z0-9]+ # (sub)domains are letters, numbers, and hyphens
\. # separated by a dot
)+ # and there can be one or more of them
(
[a-z]{2} # top level domain can be a 2-letter alpha
country code
|com|net # or one of
|edu|org # many
|gov|mil # possible
|int|biz # 3 letter
|pro # or
|info|arpa # more
|aero|coop # ICANN
|name # tlds - and more options
|museum # might be added
)
$ # anchor at the end
/ix # everything is case-insensitive
';
Here is the complete function:
/**
* Function: validate_email
* ***
* Purpose: to perform basic e-mail address validation.
* Be aware this regx is not perfect, and it is possible to fool it.
* From: PHP cookbook
* ***
* @param string $address text e-mail address
* @return bool FALSE = not valid e-mail address
* *** */
function validate_email ($address='') {
$pattern =
'/^[^@\s]+@([-a-z0-9]+\.)+([a-z]{2}|com|net|edu|org|gov|mil|int|biz|pro|info|arpa|aero|coop|name|museum)$/ix';
return preg_match ($pattern, $address);
}