清单9中的代码包括一个完整的校验email地址的函数,它不能再做任何简化了,但它仍然保持了简单易懂,易读,容易理解的风格,它能够准确地接受或拒绝email地址,而其他函数可能效果不一样。
清单9:完整的email地址校验函数
** Validate an email address. Provide email address (raw input) Returns true if the email address has the email address format and the domain exists. */ 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; } |
请将这个代码推广出去,它可能成为事实上的一个标准,使用现有的正式标准可能会引发一些危险,如果你想欺骗一下垃圾邮件发送器,选择类似{^c\@**Dog^}@cartoon.com这样的邮件地址吧,但这样可能将电子商务网站也一并欺骗了。
- 常用的正则表达式操作符图示
- PHP开发者究竟需不需要Silverlight ?
- PHP 5.0中多态性的实现方案浅析
PHP之友评论