5.5 Finding a Specific Occurrence of a Match


You want to find the n th occurrence of a certain match. For example, you want to locate the second occurrence of a word starting with the letter o in the phrase, "The quick brown fox jumped over the lazy old dog."

Technique

Use the preg_match_all() function to keep track:

 <?php $str = "The quick brown fox jumped over the lazy old dog"; // Find all the matches of 'the', $matches[2][0] will contain // the first match, and $matches[2][1] will contain the second match preg_match_all ("/(^\s+)(o\w+)($\s+)/i", $str, $matches, PREG_PATTERN_ORDER); ?> 

Comments

This is one of those places where PHP is incompatible with Perl as far as the regular expressions are concerned . In PHP, we use the preg_match_all() function to find the occurrence number we need. But in Perl 5, we use the /g modifier to specify a global match.

The preg_match_all() function returns a two-dimensional array. The structure of the array differs depending on the value of the last argument, which can be PREG_PATTERN_ORDER or PREG_SET_ORDER . (If you don't pass it, it defaults to PREG_PATTERN_ORDER .)

For PREG_PATTERN_ORDER , the results are ordered so that $matches[0] is an array of strings matched by the full pattern, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. If you use PREG_SET_ORDER , however, the results are ordered so that $matches[0] is an array of the first set of matches (starting from full match and proceeding through subpattern matches), $matches[1] is an array of second set of matches, and so on.

The following code effectively illustrates the difference:

 <?php preg_match_all ("<[^>]+>(.*)</[^>]+>U",                 "<i>Test: </i><div align=left>A Simple Experiment</div>",                 $matches,                 PREG_PATTERN_ORDER); print "{$matches[0][0]}, {$matches[0][1]}\n"; print "{$matches[1][0]}, {$matches[1][1]}\n"; ?> 

which prints:

 <i>Test: </i>, <div align=left>A Simple Experiment</div> Test: , A Simple Experiment 

The Second ( PREG_SET_ORDER ):

 <?php preg_match_all ("<[^>]+>(.*)</[^>]+>U",                 "<i>Test: </i><div align=left>A Simple Experiment</div>",                 $matches,                 PREG_SET_ORDER); print "{$matches[0][0]}, {$matches[0][1]}\n"; print "{$matches[1][0]}, {$matches[1][1]}\n"; ?> 

Yields:

 <i>Test: </i>, Test: <div align=left>A Simple Experiment</div>, A Simple Experiment 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net