3

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];
}

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

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

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!

Mike B
  • 31,886
  • 13
  • 87
  • 111
AlxVallejo
  • 3,066
  • 6
  • 50
  • 74

2 Answers2

4

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

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.

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?

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
  • You're right. $matches[0] refers to the array of matches in the whole expression. I was able to loop through the array successfully. Thanks. – AlxVallejo Nov 16 '11 at 15:20
4

If you do want to rewrite this code, then I suggest you look into PREG_SET_ORDER as last argument, instead of PREG_PATTERN_ORDER. This groups the result array by results first, and with match groups in the second level.

Then you can just loop over it as follows:

foreach ($matches as $matchgroup) {
    $postslug = $matchgroup[0];
}

You still need the [0] to get the "complete match". If your pattern had any (..) groups then [1] and [2] would correspond to those..

mario
  • 144,265
  • 20
  • 237
  • 291