0

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

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;
}
4

3 回答 3

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.
?>

活生生的例子

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

于 2010-10-06T20:39:06.543 回答
-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;
        }
    }
}

最简单的

于 2010-10-06T19:59:57.447 回答
-2

或者,与 Asar 相同但更短:

function  checkEmail($email) {
     $patern = '/^[a-zA-Z0-9.\-_]+@[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,4}$/';
     return preg_match($patern , $email);
}
于 2010-10-06T20:34:05.153 回答