2012-07-03 3 views
1

내가 다음 문자열이 말 :텍스트 문자열에서 첫 번째 일치 항목을 추출 하시겠습니까?

안녕 내 차 빨간색이고 내 신발이 파란색을

나는 다음과 같은 단어를 일치시킬

:

블루, 레드, 오렌지를 , 보라색

따라서이 변수는 4 단어를 검색하여 첫 번째 값을 반환합니다. le 단어는 'red'가됩니다. 그러나 차가 파란 경우, 가능한 한 일치하는 목록을 찾는 첫 번째 단어 인 파란색이라는 단어가 먼저 반환됩니다.

어떻게하면됩니까? 내가 제대로 질문을 이해하면

+0

죄송합니다, 확실히하지 않는다 그것 : 당신의 끈이'나의 차가 파랗고 나의 단화가 파랗다'인 경우에, 무슨 shou 돌려 주겠습니까? – raina77ow

+0

파랑, 첫 번째 것을 찾고 반환 – Latox

+0

좋아,하지만 그때 문제가 뭐야? 두 코드 모두 동일한 코드입니다. – raina77ow

답변

4
$str = 'hello my car is red and my shoe is blue'; 
$find = 'blue,red,orange,purple'; 
$pattern = str_replace(',','|',$find); 
preg_match('#'.$pattern.'#i',$str,$match); 
echo $match[0]; 

:-) 민감한

+0

잘 작동합니다. 어떻게 대소 문자를 구분하지 않습니까? – Latox

+0

@ Latox, edit.added 'i'수정 자 패턴 참조 – Lake

0

케이스 :. 문자를 구분

<?php 
$subject = "hello my car is blue and my shoe is blue";                      
$pattern = '/blue|red|orange|purple/';                          
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);                    
if (!empty($matches)) {                              
    echo 'Matched `' . $matches[0][0] . '` at index `' . $matches[0][1] . '`';                 
} else {                                  
    echo 'Nothing matched';                             
} 
?> 

케이스 :

<?php 
$subject = "hello my car is blue and my shoe is blue";                      
$pattern = '/blue|red|orange|purple/';                          
preg_match(strtolower($pattern), strtolower($subject), $matches, PREG_OFFSET_CAPTURE);                    
if (!empty($matches)) {                              
    echo 'Matched `' . $matches[0][0] . '` at index `' . $matches[0][1] . '`';                 
} else {                                  
    echo 'Nothing matched';                             
} 
?> 
0
$string = 'hello my car is red and my shoe is blue'; 
$words = array ('blue', 'red', 'orange', 'purple'); 

function checkForWords ($a, $b) { 

    $pos = 0; 
    $first = 0; 
    $new_word = ''; 

    foreach ($b as $value) { 
     $pos = strpos($a, $value); 

     # First match 
     if (!$first && $pos) { 
      $new_word = $value; 
      $first = $pos;   
     } 

     # Better match 
     if ($pos && ($pos < $first)) { 
      $new_word = $value; 
      $first = $pos; 
     } 
    } 
    return $new_word; 

} 

echo checkForWords ($string, $words); 
관련 문제