只获取指定的电子邮件名称

时间:2017-01-24 15:02:51

标签: php preg-match preg-match-all php-5.3

我遇到preg_math问题。所以我有这个方法:

public function filterUsers($a_users){

    $a_authorizedEmail = array(
        '@test.com',
        '@test1.com'
    );

    $a_response = array();
    foreach ($a_users as $user) {
        if(false !== $email_user = EmailRepository::getEmail($user['id'])){
            foreach($a_authorizedEmail as $email){
                echo $email_user;
                if(preg_match($email, $email_user)){
                    $a_response[]= $user;
                }
            }
        }
    }
    return $a_response;
}

包含$a_users的数组:我的用户的电子邮件为hcost@test.com。但在返回时,数组是空的。可能我没有做出正确的验证。请帮帮我

1 个答案:

答案 0 :(得分:1)

这样做:

public function filterUsers($a_users){

    $a_authorizedEmail = array(
        '@test.com',
        '@test1.com'
    );
    $pattern = "/".implode("|",$a_authorizedEmail)."$/"; //Note the "/" start and end delimiter as well as the $ that indicates end of line
    $a_response = array();
    foreach ($a_users as $user) {
        $email_user = EmailRepository::getEmail($user['id']);  
        if(false !== $email_user){ 
            echo $email_user;
            if(preg_match($pattern, $email_user)){
                $a_response[]= $user;
            }
        }
    }
    return $a_response;
}