P R
P R

Reputation: 1301

PHP regex examples

I am a beginner learning PHP. I am trying out various combinations with regex. I am referring to this and this and trying out examples on this.

My doubts:

  1. Why does preg_match_all('((a|b)*c)', 'ababc', $arr, PREG_PATTERN_ORDER); give both ababac and a as output. Shouldn't it be just ababac?

  2. Assuming that I'm trying to read all possible outputs in $arr, how do I do that without having to echo each element of the array? Currently, I'm using foreach to iterate the elements in $arr. Is this right / is there a better way to do it?

  3. Why does the preg_match_all() give a 2D array with elements $arr[$i][0] and in some cases $arr[0][$i] where $i is no of of possible matches. Is there a way to know how the output will be stored?

Sorry for posting too many questions in one post. Please tell me if I need to change it.

Upvotes: 1

Views: 239

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

  1. The (a|b) is a captured subpattern, therefore it is returned as part of the result array. You can make it non-capturing by using (?:a|b), but it would be far better as a character class, [ab].

  2. foreach is probably the best way to go about it.

  3. As mentioned in 1, you will get your subpatterns captured and returned in the array.

You may want to look into preg_replace_callback(), as this will apply a given callback (usually an anonymous function) to each match.

Upvotes: 3

Related Questions