Reputation: 6405
I need to filter some email address based on the domain name : Basically if the domain name is yahoo-inc.com, facebook.com, baboo.com .. (and a few others) the function should do something and if the domain is different it should do something else . The only way I know to do this is to use a pattern/regex with preg_match_all and create cases/conditions for each balcklisted domain (e.g if domain = yahoo-inc) do this elseif (domain == facebook.com ) do this ... etc but I need to know if there is a more simple/concis way to include all the domains that I want to filter in a single variable/array and then apply only 2 conditions (e.g if email is in black list {do something } else {do something else}
Upvotes: 1
Views: 3924
Reputation: 2078
Adding on to @Alnitak here is the full code to do what you need
$domain = explode("@", $emailAddress);
$domain = $domain[(count($domain)-1)];
$blacklist = array('yahoo-inc.com', 'facebook.com', ...);
if (in_array($domain, $blacklist)) {
// bad domain
} else {
// good domain
}
Upvotes: 2
Reputation: 57268
Well here's a very simple way to do this, a VALID email address should only ever contain a single @
symbol, so aslong as it validation you can just explode the string by @
and collect the second segment.
Example:
if (filter_var($user_email, FILTER_VALIDATE_EMAIL))
{
//Valid Email:
$parts = explode("@",$user_email);
/*
* You may want to use in_array if you already have a compiled array
* The switch statement is mainly used to show visually the check.
*/
switch(strtolower($parts[1]))
{
case 'facebook.com':
case 'gmail.com':
case 'googlemail.com':
//Do Something
break;
default:
//Do something else
break;
}
}
Upvotes: 1
Reputation: 339786
Extract the domain portion (i.e. everything after the last '@'), down case it, and then use in_array
to check whether it's in your blacklist:
$blacklist = array('yahoo-inc.com', 'facebook.com', ...);
if (in_array($domain, $blacklist)) {
// bad domain
} else {
// good domain
}
Upvotes: 2