home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomePHP CookbookSearch this book

13.4. Finding the nth Occurrence of a Match

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

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);

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

Library Navigation Links

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