preg_match_all多维数组输出循环?PHP

bwitn5fc  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(143)

我目前正在一个字符串上运行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
                )

        )

)

**问题:**如何循环匹配并回显编号和偏移位置?

hs1rzwqc

hs1rzwqc1#

你可以使用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

相关问题