【问题标题】:How can I get only named captures from preg_match? [duplicate]如何从 preg_match 中仅获取命名捕获? [复制]
【发布时间】:2011-12-31 18:20:28
【问题描述】:

可能重复:
how to force preg_match preg_match_all to return only named parts of regex expression

我有这个sn-p:

$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]);
}

【问题讨论】:

  • 可以使用T-Regx库,也可以使用namedGroups()方法。

标签: php regex preg-match pcre


【解决方案1】:

preg_match 将始终返回数字索引,而不考虑命名的捕获组

【讨论】:

    【解决方案2】:
    return array(
        'name' => $matches['name'],
        'likes' => $matches['likes'],
    );
    

    某种过滤器,当然。

    【讨论】:

    • foreach($matches as $k =&gt; $v) { if(is_int($k)) { unset($matches[$k]); } } 剥离数字键并仅保留已命名的键。
    • 现在 (php 5.6+) $matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY); 是实现相同目标的更简单方法。应用“is_string”作为键的过滤器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    相关资源
    最近更新 更多