【问题标题】:preg_match_all multidimensional array output looping? PHPpreg_match_all 多维数组输出循环? PHP
【发布时间】:2017-04-07 22:22:15
【问题描述】:

我目前正在使用正则表达式查找电话号码的字符串上运行preg_match_all。当它找到匹配项时,它会记下字符串中的偏移位置。

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
                )

        )

)

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

【问题讨论】:

  • 你能提供你的输入字符串吗?
  • 我正在解析的字符串是电子邮件正文内容,太长无法在此处发布,并且是私人电子邮件。所有匹配等都很好,我只需要知道如何循环遍历在上面示例中找到的数据数组。这样,如果需要,我可以将数字及其偏移位置存储到变量或数据库中。

标签: php loops multidimensional-array foreach preg-match-all


【解决方案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

【讨论】:

  • 我已经在我的代码中完成了确切的 foreach 循环,但显然,我的失败并不是专门针对 $match[0] 和 $match[1] - 谢谢!
  • @Meta 你介意我问你为什么没有正确定位他们吗?您显示了print_r() 输出,它以这种方式清楚地识别它们。作为一个在这里花费大量时间回答新手问题的人,我想知道当你能在眼前看到它时,把这样的事情做对的心理障碍是什么。
  • @Barmar 在一个项目上工作了将近 48 小时,我对多维数组并不是 100% 熟悉,最近在长时间休息后重新开始编程,所以我还是很生疏。
猜你喜欢
  • 2013-06-25
  • 2019-07-17
  • 2012-05-13
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
相关资源
最近更新 更多