問題描述
我想弄清楚這個插件在 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
循環(huán)重寫為 foreach
循環(huán),但這可能不會改變任何東西,因為這兩種方法都應該遍歷所有$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 的匹配項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!