首页/Home PHP Common Programming Email有效性的完整验证函数 (Email validation function)

Email有效性的完整验证函数 (Email validation function)

PrintE-mail
Monday, 21 January 2008 01:00  
该函数以尽可能详尽的方式验证了一个Email是否有效。

<?php
/**
* Based on the relevant RFC, the following function validates
* the format of an email address in a rather exhaustive manner.
*
* @param string $emailAddr
* @return bool
* @author Shelley Shyan
*/
function validateEmail ($emailAddr = '')
{
if (empty(
$emailAddr)) { return false; }

$laddr = '';
$laddr = $emailAddr;
$laddr = preg_replace('/^.*</', '', $laddr);
$laddr = preg_replace('/>.*$/', '', $laddr);

if (
preg_match('/^@.*:/', $laddr)) #path-relative domain
{
list(
$domain,$addr_spec) = preg_split('/:/', $laddr);
$domain = preg_replace('/^@/', '', $domain);
if (!
isDomain($domain)) { return false; }
$laddr = $addr_spec;
}
return (
isAddrSpec($laddr));
}

function
isAddrSpec ($emailAddr = '')
{
list(
$local_part,$domain) = preg_split('/@/', $emailAddr);
if (!
isLocalPart($local_part) || !isDomain($domain))
return
false;
else
return
true;
}

function
isLocalPart ($local_part = '')
{
if (empty(
$local_part)) { return false; }

$bit_array = preg_split('/./', $local_part);
while (list(,
$bit) = each($bit_array))
{
if (!
isWord($bit)) { return false; }
}
return
true;
}

function
isWord ($word = '')
{
if (
preg_match('/^".*"$/i', $word))
{
return (
isQuotedString($word));
}
return (
isAtom($word));
}

function
isQuotedString ($word = '')
{
$word = preg_replace('/^"/', '', $word); # remove leading quote
$word = preg_replace('/"$/', '', $word); # remove trailing quote
$word = preg_replace('/\+/', '', $word); # remove any quoted-pairs
if (preg_match('/"\r/', $word)) # if ", or CR, it's bad qtext
{
return
false;
}
return
true;
}

function
isAtom ( $atom = '')
{
if (
(
preg_match('/[()<>@,;:\".[]]/', $atom)) # specials
|| (preg_match('/40/', $atom)) # SPACE
|| (preg_match('/[x00-x1F]/', $atom)) # CTLs
)
{
return
false;
}
return
true;
}

function
isDomain ($domain = '')
{
if (empty(
$domain)) { return false; }

if (!
preg_match('/./', $domain)) { return false; }

$dbit_array = preg_split('/./', $domain);
while (list(,
$dbit) = each($dbit_array))
{
if (!
isSubDomain($dbit)) { return false; }
}
return
true;
}

function
isSubDomain ($subd = '')
{
if (
preg_match('/^[.*]$/', $subd)) #domain-literal
{
return(
isDomainLiteral($subd));
}
return(
isAtom($subd));
}

function
isDomainLiteral ($dom = '')
{
$dom = preg_replace('/\+/', '', $dom); # remove quoted pairs
if (preg_match('/[[]\r]/', $dom)) # bad dtext characters
{
return
false;
}
return
true;
}

?>