我试图弄清楚这个插件在 WordPress 中的机制。 我有一个 preg_match_all 函数,如下所示:
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
中只有一个匹配项。
我的目标是重写 for 语句以允许 preg_match_all
脚本中的完整匹配数组。
我假设我应该用 foreach ($matches as $postSlug)
替换 for 语句,甚至不用担心令人困惑的 $matches[0][$i]
在最后。
不幸的是,最终输出似乎没有遍历数组中的每个元素。有任何想法吗?谢谢!
最佳答案
If I understand this correctly, count($matches[0] assumes there is only one match in $content.
不完全; $matches[0]
表示整个正则表达式的匹配数组(与 $matches[1]
相对,后者将是匹配数组在正则表达式的第一个匹配组中)。因此,count($matches[0])
是他第一个匹配组中的匹配数。
你可以照你说的做,将 for
循环重写为 foreach
循环,但这可能不会改变任何事情,因为这两种方法都应该遍历所有$matches[0]
中的元素。您确定要查找的结果与您的正则表达式匹配吗?
关于php - 从 preg_match_all 迭代匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8127288/