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