2

我需要拆分这种字符串来分隔小于和大于< >之间的电子邮件。我正在尝试下一个regexand 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);
}
4

6 回答 6

2

拆分某些内容会删除分隔符(即正则表达式匹配的所有内容)。你可能想分开

\s*<|>

反而。或者您可以使用preg_match正则表达式

^(.*?)\s*<([^>]+)>

并使用第一和第二捕获组。

于 2012-07-19T10:20:40.770 回答
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
)
于 2012-07-19T10:26:03.757 回答
1

这将完成这项工作。单击此处获取键盘链接

$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);
于 2012-07-19T10:41:08.047 回答
0
preg_match_all("/<(.*?)>/", $string, $result_array);
print_r($result_array);
于 2012-07-19T10:25:57.350 回答
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 ) ) 
于 2012-07-19T10:26:26.123 回答
0

你也可以用 < 分割,并去掉 $result 中的 ">"

  $pattern = '/</';
  $result = preg_split($pattern, $email);
  $result = preg_replace("/>/", "", $result);
于 2012-07-19T10:26:55.417 回答