Return 匹配 preg_match 没有带数字键的项目

Return matches with preg_match without items with numerical keys

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

print_r($matches);

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

我希望 $matches 只包含 'name' 和 'digit' 值,而不通过迭代删除其他值。

有没有更快的方法? preg_match 默认情况下 return 对我来说只能是字符串类型的键吗?

注:以上preg_match为示例。我想要任何输入的解决方案。

没有 "simple" 方法,因为 preg_match 没有这样的选项来只输出命名组。

如果您必须从数组中删除带有数字键的项目并且不想使用显式循环,您可以使用此 array_filter 解决方法:

$str = 'foobar: 2008';
if (preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches)) {
    print_r(
      array_filter($matches, function ($key) { return !is_int($key); }, ARRAY_FILTER_USE_KEY)
    );
} // => Array ( [name] => foobar [digit] => 2008 )

PHP demo