用于验证电子邮件地址的功能

时间:2010-10-06 19:29:39

标签: php email-address

我正在使用此功能验证电子邮件地址, 但如果电子邮件地址是这样的话,它就不起作用了:

name@server.com. 
OR 
//name@server.com

有没有办法开发这个功能?

function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

3 个答案:

答案 0 :(得分:1)

使用 filter_var() 。下面是一个简单的使用演示。还有许多其他选择。

<?php

  // You might want to trim whitespace first: 
$possibleEmailAddress = trim($possibleEmailAddress);

filter_var($possibleEmailAddress, FILTER_VALIDATE_EMAIL);

// Returns false if $possibleEmailAddress doesn't appear valid.
// Returns the email string if it does appear okay.
?>

<强> live example

请注意,//name@server.com是有效的电子邮件,但name@server.com.不是。您必须从结尾修剪周期才能使其有效。您不能只使用trim(),因为电子邮件开头的句点可能是有效且有意的。

答案 1 :(得分:-2)

function  checkEmail($email) 
    {
    $patern = '/^[a-zA-Z0-9.\-_]+@[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,4}$/';
    if (preg_match($patern , $email)) 
        {
        return TRUE;
        }
    else
        { 
        return FALSE;
        }
    }
}

最简单的

答案 2 :(得分:-2)

或者,与Asar相同但更短:

function  checkEmail($email) {
     $patern = '/^[a-zA-Z0-9.\-_]+@[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,4}$/';
     return preg_match($patern , $email);
}