【发布时间】: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