2016-11-23 258 views
2

我目前正在使用正则表达式查找电话号码的字符串上运行preg_match_all。当它找到匹配时,它会记录字符串中的偏移位置。preg_match_all多维数组输出循环? PHP

preg_match_all示例:

preg_match_all('/\b\/?\d?[-.]?\s?\(?\d{3}\)?\s?[-.]?\d{3}[-.]?\d{4}\b/', $string, $matches, PREG_OFFSET_CAPTURE); 

使用的print_r

echo print_r($matches, true).BR; 

输出:

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [0] => 666.666.6666 
        [1] => 1190 
       ) 

      [1] => Array 
       (
        [0] => 555-555-5555 
        [1] => 1206 
       ) 

     ) 

) 

问题:如何循环搜索并回显数字和偏移位置?

+0

你能提供您输入的字符串? –

+0

我正在解析的字符串是电子邮件正文内容,并且太长,无法在此处发布,并且是私人电子邮件。所有的匹配和这样的都很好,我只需要知道如何循环访问上面示例中找到的数据。这样我可以将数字和偏移位置都存储到变量或数据库中(如果需要的话)。 – Meta

回答

1

你可以使用一个foreach循环:

foreach ($matches[0] as $match) { // use first array item to loop through since the matches are in its sub-array 
    echo "Number = " . $match[0] . " | Offset = " . $match[1] . "\r\n"; 
} 

输出:

Number = 666.666.6666 | Offset = 1190 
Number = 555.555.5555 | Offset = 1206 
+0

我已经在我的代码中完成了foreach循环,但显然,我的失败并不是专门针对$ match [0]&$ match [1] - 谢谢! – Meta

+0

不客气。很高兴帮助。 – JazZ

+0

@Meta你介意我问你为什么没有正确定位它们?您显示了'print_r()'输出,它清楚地标识了它们。作为一个在这里花费大量时间回答新手问题的人,我想知道当你能够在眼前看到这些东西时,让这样的事情发生的心理障碍是什么。 – Barmar