This question was asked in a recent job interview I gave and I was unable to answer it. Here is the question:
From a given email list (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com) extract only those emails ending with (@noemail.com, @no-email.com, and @no email.com).
I searched and tried to run the code but it didn't ran.
<?php
$email_list = (johndoe@noemail.com, xyz@no-email.com, noemail@xyz.com, answers@no email.com, jpt@nooooemail.com, kondoe@nomail.com);
$pattern = ('@noemail.com', '@no-email.com', '@no email.com' );
echo preg_match($pattern, $email_list);
?>
<?php
$email_list = array("johndoe@noemail.com", "xyz@no-email.com", "noemail@xyz.com", "answers@no email.com", "jpt@nooooemail.com", "kondoe@nomail.com");
$matchlist = array("@noemail.com", "@no-email.com", "@no email.com");
function str_contains($haystack, $needle) {
return (strpos($haystack, $needle) !== false);
}
foreach ($email_list as $email) {
foreach($matchlist as $match) {
if (str_contains($email, $match)) {
echo $email . "<br>";
break;
}
}
}
Not the perfect way, but works.
$email_list = array('johndoe@noemail.com', 'xyz@no-email.com',
'noemail@xyz.com', 'answers@no email.com',
'jpt@nooooemail.com', 'kondoe@nomail.com');
$result = array();
foreach ($email_list as $email) {
if (preg_match('~@no[ -]?email\.com~', $email)) {
$result[] = $email;
}
}
var_export($result);
// output ->
// array (
// 0 => 'johndoe@noemail.com',
// 1 => 'xyz@no-email.com',
// 2 => 'answers@no email.com',
// )