preg_match_all 输出 PHP 中的奇怪数组结构

Weird array structure in preg_match_all output PHP

我有 pregmatch_all 功能可以 抓取 电子邮件!但是输出的结构有点奇怪,我无法对其进行重组。

$str = "Service Client ouvert : du lundi au vendredi de 9h à 20h le samedi de 9h à 18h 01 75 85 83 83 hello@soshape.com So Shape France / Site créé par KL Consult"
$pattern = '/[a-z0-9_\-\+\.]+@[a-z0-9\-]+\.([a-z]{2,4})(?:\.[a-z]{2})?/i';
$preg_match_all($pattern, $str, $output);
print_r($output);

returns

Array ( [0] => Array ( [0] => hello@soshape.com ) [1] => Array ( [0] => com ) )

请注意两件事:

有什么想法吗? (如果我的问题不清楚,请随时告诉我。我很乐意进一步解释!)

正如 Markus 在评论中所写,让我们看看 PREG_PATTERN_ORDER 标志:

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

来自文档here

因为你的 patten 包括 ()([a-z]{2,4}) 一样 .com 也被捕获了。

如果您只想要电子邮件,您可以使用 PREG_PATTERN_ORDER,它将 return 匹配 return 数组的索引 0(因为您不需要带括号的子模式您可以忽略以下索引)

所以你可以这样做:

$preg_match_all($pattern, $str, $output, PREG_PATTERN_ORDER);
print_r($output[0]);