php - 我怎样才能只从 preg_match 中获取命名的捕获?

标签 php regex preg-match pcre

<分区>

Possible Duplicate:
how to force preg_match preg_match_all to return only named parts of regex expression

我有这个片段:

$string = 'Hello, my name is Linda. I like Pepsi.';
$regex = '/name is (?<name>[^.]+)\..*?like (?<likes>[^.]+)/';

preg_match($regex, $string, $matches);

print_r($matches);

这打印:

Array
(
    [0] => name is Linda. I like Pepsi
    [name] => Linda
    [1] => Linda
    [likes] => Pepsi
    [2] => Pepsi
)

我怎样才能让它返回:

Array
(
    [name] => Linda
    [likes] => Pepsi
)

无需对结果数组进行过滤:

foreach ($matches as $key => $value) {
    if (is_int($key)) 
        unset($matches[$key]);
}

最佳答案

preg_match 将始终返回数字索引,而不管命名的捕获组如何

关于php - 我怎样才能只从 preg_match 中获取命名的捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174749/

相关文章:

Java:递归模式搜索文件(具有相对路径)以作为变量传递

java - 如何使用正则表达式查找字符串是否至少有一个字符?

PHP preg_match 范围

php - preg_match 用户名验证正则表达式允许 > 和 < 尽管这些字符未列入白名单

php - 如何计算表中的行数 (phpMyAdmin)

php - MongoDB PHP 限制字段的返回值

java - 要分割的正则表达式 (...,...)

php - 为什么我不能 str_replace?

php - CakePHP 3 错误 : The application is trying to load a file from the DebugKit plugin

php - WordPress 获取 nav_menu_submenu_css_class 过滤器中的显示位置