具有相同模式的输出值

时间:2014-11-10 09:47:32

标签: php arrays output

我在php中有这个代码:

<?php
    $mails_list = "user1@example.com, User 2 <user2@example.com>, User 3 (user3@example.com)";
    $mails_arr = explode(',', $mails_list);
    foreach($mails_arr as $mail){
        echo "{$mail}<br>";
    }
?>

请注意,使用该代码,他的输出将为:

user1@example.com
User 2 <user2@example.com>
User 3 (user3@example.com)

我不想那样。我想要的是输出必须是:

user1@example.com
user2@example.com
user3@example.com

我怎么能用PHP做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用preg_match_all()使用正则表达式捕获所有电子邮件:

preg_match_all('/[<(]?(\w+@\w+\.\w+)[>)]?/', $mails_list, $matches);
echo implode("\n", $matches[1]);

Demo

答案 1 :(得分:2)

你走了,

<?php
$mails_list = "user1@example.com, User 2 <user2@example.com>, User 3 (user3@example.com)";
$mails_arr = explode(',', $mails_list);

preg_match_all('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/i', $mails_list, $found_mails);

foreach ($found_mails[0] as $each)  { echo $each.'<br>'; }