preg_match_all()中没有找到匹配项时的第三个参数的类型


The type of the third parameter in preg_match_all() when no matches are found

我在我的项目中使用preg_match_all()来查找给定字符串中的匹配。例如:

preg_match_all( $pattern, $subject, $matches, $flags );

如果找到匹配项,则$matches参数将是根据$flags排序的匹配项的多维数组。

如果没有找到匹配,$matches是什么类型?它仍然是一个数组,尽管是一个空数组,还是会是其他的东西,如falsenull ?

裁判:http://php.net/manual/en/function.preg-match-all.php

您将不会得到一个空数组,而是一个由一个或多个空数组组成的数组,这取决于您的regex中的捕获组。查看差异:

preg_match_all('/foo/', 'bar', $matches);
print_r($matches);
Array
(
    [0] => Array ( )
)
preg_match_all('/(f)oo/', 'bar', $matches);
print_r($matches);
Array
(
    [0] => Array ( )
    [1] => Array ( )
)

$matches将是一个包含空子数组的数组。这是你可以很容易地自己测试的东西。

<?php
preg_match_all('/O/', 'foo', $matches);
var_dump($matches);
输出:

array(1) {
  [0]=>
  array(0) {
  }
}

一个简单的测试将告诉您:

preg_match_all("/[0-9]/", "Hello World", $matches);
var_dump($matches);
array(1) { 
  [0]=> array(0) { 
  } 
}