Reputation: 856
I need to check if the email id provided by the user ends with aa.bb.cc
For example if the user provides an email id [email protected]
i want the check to only be placed on aa.bb.cc
collegename can be whatever it does not matter but the id must end with aa.bb.cc
So to achieve it I tried
$value = '[email protected]';
$explodedEmail = explode('@', $value);
$domain = array_pop($explodedEmail);
This gives me an output of
collegename.aa.bb.cc
So how can I place a check where the collegename
is ignored and i have just aa.bb.cc
Upvotes: 2
Views: 202
Reputation: 20286
Actually it's pretty trivial
// Check if email is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
list($user,domain) = explode('@', $email);
if ($domain === 'yourdomain.com') {
// here goes logic if domain is valid
}
}
There are also other options:
check if string ends with domain.com with substr() startsWith() and endsWith() functions in PHP
function endsWith($haystack, $needle) {
// search forward starting from end minus needle length characters
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if ($endsWith($email) === 'aa.bb.cc') {
// here goes logic if domain is valid
}
}
preg_split/preg_match to extract valid domain
But in the most cases first one will work
Upvotes: 0
Reputation: 514
You can use a regular expression to detect this:
preg_match("\aa\.bb\.cc$\", $value)
This return true if the email ends in aa.bb.cc
If you want more information: http://php.net/manual/en/function.preg-match.php
Upvotes: 0
Reputation: 1828
You could just use explode (again), this time with a added limit:
$dot = explode('.',$domain,2);
Which prints out
Array
(
[0] => collegename
[1] => aa.bb.cc
)
And then it would be a simple matter of matching against $dot[1]
Upvotes: 2
Reputation: 42984
Take a look at "regular expressions" and how functions like preg_match() work. Read its documentation for that, it comes with good examples: http://php.net/manual/en/function.preg-match.php
A simple example would be such code:
<?php
$subject = '[email protected]';
$pattern = '/^([^@]+)@([^.]+)\.(.+)$/';
preg_match($pattern, $subject, $tokens);
var_dump($tokens);
The output is:
array(4) {
[0] =>
string(25) "[email protected]"
[1] =>
string(4) "name"
[2] =>
string(11) "collegename"
[3] =>
string(8) "aa.bb.cc"
}
To make a more specific test against the domain aa.bb.cc
and not match anything else you could use a more specific regular expression:
$pattern = '/^([^@]+)@([^.]+)\.aa\.bb\.cc$/';
So regular expressions offer a very flexible tool to separate tokens inside a subject string. To develop more complex matching patterns online regex tools are available for example https://regex101.com/
Upvotes: 1