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

时间:2015-11-24 07:26:05

标签: php arrays email email-validation domain-name

I've an array of email ids. I want to check each and every email id for it's domain. Actually, I've to parse over this array whenever there is email id found with no '.edu' domain, error message should be thrown as 'Please enter valid .edu id' and further emails from the array should not be checked.

How should I achieve this in efficient and reliable way?

Following is my code of array which contains the email ids. The array could be empty, contain single element or multiple element. It should work for all of these scenarios with proper validation and error messages.

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

$aVals['invite_emails'] contains the list of email ids received in request.

Please let me know if you need any further information regarding my requirement if it's not clear to you.

Thanks in advance.

2 个答案:

答案 0 :(得分:2)

你可以这样做,

<强>更新

// 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
        }
    }
}

答案 1 :(得分:2)

由于电子邮件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";
            }
    }
}