2011-11-17 1 views
9

가능한 중복 :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
how to force preg_match preg_match_all to return only named parts of regex expression

나는이 조각을 가지고 다만 반환을 T :

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

결과 배열의 필터링에 의존하지 않고 :

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

답변

6

preg_match를 항상라는 포착기로없이

3
return array(
    'name' => $matches['name'], 
    'likes' => $matches['likes'], 
); 

필터, 반드시 어떤 종류.

+5

'의 foreach { 경우 (is_int ($ K)) { 해제 ($ 일치 [$ ($ K => $ V 등 $ 일치) 수치 인덱스를 반환 케이]); } }'숫자 키를 제거하고 명명 된 키만 삭제합니다. – Radu

관련 문제