如何检查电子邮件id';s具有电子邮件id数组中的特定域';s在PHP中


How to check email id's with specific domain from the array of email id's in PHP?

我有一组电子邮件id。我想检查每个电子邮件id的域名。事实上,每当发现没有".edu"域的电子邮件id时,我都必须对此数组进行分析,错误消息应该被抛出为"请输入有效.edu id",并且不应该检查来自该数组的其他电子邮件。

我应该如何以高效可靠的方式实现这一点?

以下是我的数组代码,其中包含电子邮件ID。数组可以为空、包含单个元素或多个元素。它应该适用于所有这些具有正确验证和错误消息的场景。

$aVals = $request_data;
$aVals['invite_emails'] = implode(', ', $aVals['invite_emails']);

$aVals['invite_emails']包含在请求中收到的电子邮件ID的列表。

如果您不清楚我的要求,请告诉我是否需要任何进一步的信息。

提前谢谢。

您可以这样做

更新:

// consider $aVals['invite_emails'] being your array of email ids
// $aVals['invite_emails'] = array("rajdeep@mit.edu", "subhadeep@gmail.com");
if(!empty($aVals['invite_emails'])){  //checks if the array is empty
    foreach($aVals['invite_emails'] as $email){  // loop through each email
        $domains = explode(".",explode("@",$email)[1]); // extract the top level domains from the email address
        if(!in_array("edu", $domains)){  // check if edu domain exists or not
            echo "Please enter valid .edu id";
            break;  // further emails from the array will not be checked
        }
    }
}

由于电子邮件id总是由3个字符组成,您也可以这样做:

foreach($aVals['invite_emails'] as $email){
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // valid email
           if(substr($email, -3) != "edu") {
                echo "Please enter valid .edu id";
            }
    }
}