我需要拆分这种字符串,将电子邮件分隔为小于和大于< > 即可。我正在尝试下一个regex
和preg_split
,但我不行。
"email1@domain.com" <email1@domain.com>
News <news@e.domain.com>
Some Stuff <email-noreply@somestuff.com>
预期结果将是:
Array
(
[0] => "email1@domain.com"
[1] => email@email.com
)
Array
(
[0] => News
[1] => news@e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply@somestuff.com
)
我现在使用的代码:
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email);
print_r($result);
}
答案 0 :(得分:2)
拆分某些东西会删除分隔符(即正则表达式匹配的所有内容)。你可能想分开
\s*<|>
代替。或者您可以将preg_match
与正则表达式
^(.*?)\s*<([^>]+)>
并使用第一个和第二个捕获组。
答案 1 :(得分:2)
您可以使用preg_split
可用的部分标记:PREG_SPLIT_DELIM_CAPTURE
和 PREG_SPLIT_NO_EMPTY
。
$emails = array('"email1@domain.com" <email1@domain.com>', 'News <news@e.domain.com>', 'Some Stuff <email-noreply@somestuff.com>');
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($result);
}
这会输出您的期望:
Array
(
[0] => "email1@domain.com"
[1] => email1@domain.com
)
Array
(
[0] => News
[1] => news@e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply@somestuff.com
)
答案 2 :(得分:1)
这将完成这项工作。 click here for Codepad link
$header = '"email1@domain.com" <email1@domain.com>
News <news@e.domain.com>
Some Stuff <email-noreply@somestuff.com>';
$result = array();
preg_match_all('!(.*?)\s+<\s*(.*?)\s*>!', $header, $result);
$formatted = array();
for ($i=0; $i<count($result[0]); $i++) {
$formatted[] = array(
'name' => $result[1][$i],
'email' => $result[2][$i],
);
}
print_r($formatted);
答案 3 :(得分:0)
preg_match_all("/<(.*?)>/", $string, $result_array);
print_r($result_array);
答案 4 :(得分:0)
$email='"email1@domain.com" <email1@domain.com>
News <news@e.domain.com>
Some Stuff <email-noreply@somestuff.com>';
$pattern = '![^\>\<]+!';
preg_match_all($pattern, $email,$match);
print_r($match);
输出:
Array ( [0] => Array (
[0] => "email1@domain.com"
[1] => email1@domain.com
[2] => News
[3] => news@e.domain.com
[4] => Some Stuff
[5] => email-noreply@somestuff.com ) )
答案 5 :(得分:0)
您也可以按&lt ;,拆除“&gt;”在$ result
中 $pattern = '/</';
$result = preg_split($pattern, $email);
$result = preg_replace("/>/", "", $result);