I'm trying to understand how subpatterns work and I am a little confused about something:
$var2 = 'cat dog cow moose bat';
$match = preg_match(
"/(dog)/",
$var2,
$arr
);
var_dump($arr);
array(2) { [0]=> string(3) "dog" [1]=> string(3) "dog" }
I'm not sure why there are 2 elements in the array. Reading my php book (quote from book blow) I'm assuming the 0th element in the array is the match of the entire string while the second element is the match of just the substring. Is this correct? Just want to make sure I understand this.
"The zeroth element of the array is set to the entire string being matched against. The first element is the substring that matched the first subpattern (if there is one), the second element is the substring that matched the second subpattern, and so on."
Extract from preg_match()
documentation :
If matches is provided, then it is filled with the results of search.
$matches[0]
will contain the text that matched the full pattern,
$matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.
Then, with /(dog)/
regex, you'll have :
$matches[0]
containing /(dog)/
results (full pattern)$matches[1]
containing (dog)
results (first capturing group)If your first capturing group is equal to you full pattern, then match[0] = match[1]
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句