Reputation: 1301
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:
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
?
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?
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
Reputation: 324620
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]
.
foreach
is probably the best way to go about it.
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