9
可能重复:
how to force preg_match preg_match_all to return only named parts of regex expression如何从preg_match获取命名捕获?
我有这样的片段:
$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
)
我怎么能GE t将其刚刚返回:
Array
(
[name] => Linda
[likes] => Pepsi
)
而不诉诸结果数组的过滤:
foreach ($matches as $key => $value) {
if (is_int($key))
unset($matches[$key]);
}
'的foreach { 如果(is_int($ k))的{ 未设置($比赛[$(为k $ => $ V $匹配) K]); } }'去掉数字键并保留唯一的名字。 – Radu