Search code examples
phppreg-matchpreg-match-allphp-5.3

Get only a specified name of email


I have a problem with preg_math. So I have this methode :

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

The array with $a_users : I have a user with email [email protected]. But in the return the array is empty. Probably I doen't made a correct verification. Please help me


Solution

  • Do this:

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