preg_match_all print *all* matches

我的梦境 提交于 2020-01-11 06:52:54

问题


I need to print all matches using preg_match_all.

$search = preg_match_all($pattern, $string, $matches);

foreach ($matches as $match) {
    echo $match[0];
    echo $match[1];
    echo $match[...];
}

The problem is I don't know how many matches there in my string, and even if I knew and if it was 1000 that would be pretty dumb to type all those $match[]'s.


回答1:


The $match[0], $match[1], etc., items are not the individual matches, they're the "captures".

Regardless of how many matches there are, the number of entries in $matches is constant, because it's based on what you're searching for, not the results. There's always at least one entry, plus one more for each pair of capturing parentheses in the search pattern.

For example, if you do:

$matches = array();
$search = preg_match_all("/\D+(\d+)/", "a1b12c123", $matches);
print_r($matches);

Matches will have only two items, even though three matches were found. $matches[0] will be an array containing "a1", "b12" and "c123" (the entire match for each item) and $matches[1] will contain only the first capture for each item, i.e., "1", "12" and "123".

I think what you want is something more like:

foreach ($matches[1] as $match) {
    echo $match;
}

Which will print out the first capture expression from each matched string.




回答2:


Does print_r($matches) give you what you want?




回答3:


You could loop recursively. This example requires SPL and PHP 5.1+ via RecursiveArrayIterator:

foreach( new RecursiveArrayIterator( $matches ) as $match )
    print $match;


来源:https://stackoverflow.com/questions/1597714/preg-match-all-print-all-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!