Book HomePHP CookbookSearch this book

13.4. Finding the nth Occurrence of a Match

13.4.1. Problem

You want to find the nth word match instead of the first one.

13.4.2. Solution

Use preg_match_all( ) to pull all the matches into an array; then pick out the specific matches you're interested in:

preg_match_all ("/$pattern/$modifiers", $string, $matches)

foreach($matches[1] as $match) {
    print "$match\n";
}

13.4.3. Discussion

Unlike in Perl, PHP's Perl-compatible regular expressions don't support the /g modifier that allows you to loop through the string one match at a time. You need to use preg_match_all( ) instead of preg_match( ).

The preg_match_all( ) function returns a two-dimensional array. The first element holds an array of matches of the complete pattern. The second element also holds an array of matches, but of the parenthesized submatches within each complete match. So, to get the third potato, you access the third element of the second element of the $matches array:

$potatoes = 'one potato two potato three potato four';
preg_match_all("/(\w+)\s+potato\b/", $potatoes, $matches);
print $matches[1][2];
three

Instead of returning an array divided into full matches and then submatches, preg_match_all( ) returns an array divided by matches, with each submatch inside. To trigger this, pass PREG_SET_ORDER in as the fourth argument. Now, three isn't in $matches[1][2], as previously, but in $matches[2][1].

Check the return value of preg_match_all( ) to find the number of matches:

print preg_match_all("/(\w+)\s+potato\b/", $potatoes, $matches);
3

Note that there are only three matches, not four, because there's no trailing potato after the word four in the string.

13.4.4. See Also

Documentation on preg_match_all( ) at http://www.php.net/preg-match-all.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.