爆炸然后选择正确的电子邮件?

时间:2011-07-07 15:32:03

标签: php arrays

我有一个看起来像这样的字符串:

email@domain1.com | email@domain5.com

我只需要匹配'domain5'的电子邮件。

$domain_needle  = 'domain5.com';
$employer_email = 'email@domain1.com|email@domain5.com';
$employer_email = explode('|', $employer_email);

如何选择具有domain5的数组成员?

使用substr_count()?

2 个答案:

答案 0 :(得分:1)

$domain_needle  = 'domain5.com';
$employer_email = 'email@domain1.com|email@domain5.com';
$employer_email = explode('|', $employer_email);

foreach($employer_email as $email){
    if(strpos($email, $domain_needle) !== false){
        $employer_email = $email;
        break;
    }
}

echo $employer_email;

答案 1 :(得分:1)

您可以使用preg_grep

$result = preg_grep("/$domain_needle/", $employer_email);

示例,array_shift从返回的数组中提取第一个值:

$domain_needle  = 'domain5.com';
$employer_email = 'email@domain1.com|email@domain5.com';
$employer_email = explode('|', $employer_email);
print array_shift(preg_grep("/$domain_needle/", $employer_email));

输出:

email@domain5.com