Jump to content

[SOLVED] preg_match, preg_match_all, and $matches


kratsg

Recommended Posts

Is it just me, or does the topic of $matches always seem to bug me a little bit? IE: how the array for $matches is compiled, exactly what goes in what for different situations, etc...

 

For me, I'm always a little irked with this guy, like I can never remember EXACTLY what $matches[0][0] would be, etc...

 

Does anyone have a simple way of comprehending this (and don't refer to the php manual, cause that thing just seems to make it more complex than it actually is).

Element 0 is always the full pattern matches, and elements 1 and up are the individual matches.  That's all there is to preg_match()

 

For preg_match_all(), it depends on whether you set PREG_PATTERN_ORDER or PREG_SET_ORDER.  Thay may lead to some confusion..

 

Basically PREG_PATTERN_ORDER means element 0 is an array of all the full pattern matches, and elements 1 and up are arrays of individual matches.  Try var_dump() on an example and it'll make sense.

 

PREG_SET_ORDER is the other option.. you basically get an array of the arrays you WOULD have gotten if you'd run preg_match() lots of times.  Just imagine you kept running preg_match() and put all the results into a big array.  That's PREG_SET_ORDER.

 

preg_match_all('|(a)(b)|', 'ababab', &$matches); # Default to PREG_PATTERN_ORDER
var_dump($matches);
preg_match_all('|(a)(b)|', 'ababab', &$matches, PREG_SET_ORDER);
var_dump($matches);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.