PHP: Trying to understand subpattern regex match

red888

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

zessx

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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

PHP Regex match specific site url with params

来自分类Dev

PHP / preg_match / regex格式

来自分类Dev

Trying to understand the Git Workflow

来自分类Dev

PHP-regex / preg_match_all(child)简码属性

来自分类Dev

preg_match():PHP Regex上的文本范围混乱

来自分类Dev

PHP regex preg_match 在 url 中分离变量

来自分类Dev

PHP regex preg_match 来识别 url 模式

来自分类Dev

Student trying to understand callback functions

来自分类Dev

Trying to understand a simple Linux code

来自分类Dev

Wrong RegEx match in Dart

来自分类Dev

Jquery Value match Regex

来自分类Dev

Regex multiple match substring

来自分类Dev

Search/Match regex in Python

来自分类Dev

Trying to understand why this Python code works

来自分类Dev

php preg_match和regex正则表达式

来自分类Dev

PHP Regex preg_match_all div ID不相同

来自分类Dev

php preg_match和regex正则表达式

来自分类Dev

为什么[regex] match()和-match不同?

来自分类Dev

为什么[regex] match()和-match不同?

来自分类Dev

Regex to match and limit character classes

来自分类Dev

Shortest match in regex from end

来自分类Dev

std :: regex_match与字符éèà

来自分类Dev

C ++ regex_match行为

来自分类Dev

Codeigniter regex_match与比较

来自分类Dev

Trying to write REGEX for username validation in Rails

来自分类Dev

查找Regex.Match失败的地方

来自分类Dev

C ++无法使regex_match正常工作

来自分类Dev

How to dynamically create regex to use in .match Javascript?

来自分类Dev

Javascript regex match()返回匹配的部分(子集)