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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.