遍历preg_match_all中的匹配项 [英] Iterating over matches from preg_match_all

查看:223
本文介绍了遍历preg_match_all中的匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清WordPress中此插件的机制. 我有一个preg_match_all函数,如下所示:

I am trying to figure out the mechanics of this plugin in WordPress. I have a preg_match_all function that looks like this:

preg_match_all('/(?<=\\[\\[).+?(?=\\]\\])/', $content, $matches, PREG_PATTERN_ORDER);
$numMatches = count($matches[0]);

for ($i = 0; $i < $numMatches; $i++) {
  $postSlug = $matches[0][$i];
}

如果我理解正确,则count($matches[0])假定$content中只有一个匹配项.

If I understand this correctly, count($matches[0]) assumes there is only one match in $content.

我在这里的目标是重新编写for语句,以允许preg_match_all脚本中的所有匹配项.

My goal here is to re-write the for statement to allow for the full array of matches in the preg_match_all script.

我假设我应该用foreach ($matches as $postSlug)代替for语句,而不必担心最后使用混乱的$matches[0][$i].

I'm assuming I should replace the for statement with foreach ($matches as $postSlug) and not even bother with the confusing $matches[0][$i] at the end.

不幸的是,最终输出似乎没有遍历数组中的每个元素.有任何想法吗?谢谢!

Unfortunately the final output does not seem to loop through each element in the array. Any ideas? Thanks!

推荐答案

如果我理解正确,count($ matches [0]假定$ content中只有一个匹配项.

If I understand this correctly, count($matches[0] assumes there is only one match in $content.

不完全; $matches[0]表示整个正则表达式中的匹配项数组(与$matches[1]相反,它是正则表达式的第一个匹配组中的匹配项数组).因此,count($matches[0])是第一个比赛组中的比赛次数.

Not quite; $matches[0] represents the array of matches in of the whole regular expression (as opposed to, say, $matches[1], which would be the array of matches in the first match group of the regular expression). Thus, count($matches[0]) is the number of matches in he first match group.

您可以按照您所说的那样将for循环重写为foreach循环,但这可能不会改变任何内容,因为这两种方法都应遍历$matches[0]中的所有元素.您确定要查找的结果与您的正则表达式匹配吗?

You could do what you've said and rewrite the for loop as a foreach loop, but this likely won't change anything, as both methods should traverse all elements in $matches[0]. Are you certain that the results you're looking for are matched in your regular expression?

这篇关于遍历preg_match_all中的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆