是否仅将电子邮件地址限制为一个顶级域(TLD)


Restrict email address to one top level domain (TLD) only?

在以下代码中,如何将电子邮件地址限制为.edu?

function ValidateEmail($email) {
    global $debug;
    if($debug)
        return TRUE;
    else
        return preg_match("/^[^'s]+@[^'s]+.[^'s]+$/", $email);
}

PHP 5.2或更高版本使用此代码进行检查

function validateEmailAddress($email) {
  return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+'.edu/', $email);
}

好吧,验证任何电子邮件的regexp都是非常原始和不完整的,但假设这对你来说足够好,你只需要在末尾显式添加".edu",而不是[^''s]+,就像这样:

return preg_match("/^[^'s]+@[^'s]+''.edu$/", $email);

我是reg表达式的新手。但你可以看到,在这段时间后,有这个块:[^'s]+。胡萝卜(^(表示不是,'' s表示空白(制表符、换行符、空格(,+表示匹配这些字符,直到到达正则表达式的下一部分(恰好是末尾(。这意味着在电子邮件域中的.之后,您的脚本将匹配无限的非空白字符。这意味着example@test.comexample@test.comcomcomcomcomcom都可以工作,但example@test.c om不能。用edu替换此[^'s]+应该可以。

function ValidateEmail($email) {
    global $debug;
    if($debug)
        return TRUE;
    else
        return preg_match("/^[^'s]+@[^'s]+.edu$/", $email);
}

如果这不起作用(因为我不太懂regexp(,我会合并PHP的substr((。

function ValidateEmail($email) {
    global $debug;
    if($debug)
        return TRUE;
    else {
        if(substr($email,-4) != '.edu'))
             return false;
        else   // ends in .edu, check for valid email
             return preg_match("/^[^'s]+@[^'s]+.[^'s]+$/", $email);
    }
}
    preg_match("/^[^'s]+@[^'s]+.[^'s]+$/", $email);

在这个模式中,.edu应该放在模式的末尾:

    preg_match("/^[^'s]+@[^'s]+(.[^'s]+)*('.edu)$/", $email);

查看

function ValidateEmail($email) { 
    if(filter_var($email, FILTER_VALIDATE_EMAIL)  && ( substr($email ,-4) == ".edu")){
        return true;
    }else{
        return false;
    }
}