我如何限制特殊字符,除了下划线,连字符和点在电子邮件字段在PHP


How do I restrict special characters except underscore, hyphen and dot in email field in PHP?

这是我的代码。

function emailField($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);   
}

if(emailField($_POST['email'])=='')
  {
    echo "Invalid email";
  }
  else
  {
  echo "Valid";
  }

允许使用所有特殊字符。我想只允许下划线,连字符和点。如何避免?

使用RegEx:

/^['w'.]+@/

那么你还应该检查这个域是否真的存在。

PHP:

$regex = "/^['w'.]+@/";
$email = emailField($_POST['email']);
$domain = preg_replace($regex, '', $email); //get the domain of the email address by removing the local-part
//Using checkdnsrr we are checking if this domain is registred
if($email == '' && preg_match($regex, $email) && checkdnsrr($domain)){
  echo "Valid";
}

参见:http://php.net/manual/en/function.checkdnsrr.php

同时使用复杂的filter_var验证和简单的preg_match验证

function validate_email_popularly($email) {
    return
        filter_var($email, FILTER_VALIDATE_EMAIL)
        && preg_match('/'A['w.-]*+@['w.-]*+'z/', $email)
    ;
}

你也应该用filter_input代替$_POST。该函数可以过滤未预料到的Notice: Undefined index or Array into False .

$email = filter_input(INPUT_POST, 'email');
echo validate_email_popularly($email) ? 'Valid' : 'Invalid';