我在最近的一次面试中询问了这个问题,我无法回答。这是一个问题:
从给定的电子邮件列表(johndoe@noemail.com,xyz @ no-email.com,noemail @ xyz.com,answer @ no email.com,jpt @ nooooemail.com,kondoe @ nomail.com)仅提取那些以(@ noemail.com,@ no-email.com和@no email.com)结尾的电子邮件。
我搜索并尝试运行代码,但它没有运行。
<?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);
?>
答案 0 :(得分:1)
$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',
// )
答案 1 :(得分:0)
<?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;
}
}
}
不是完美的方式,但有效。