2012-07-03 100 views
1

說我有以下字符串:從文本字符串中提取第一個匹配項?

你好我的車是紅色的,我的鞋是藍色

我想匹配下面的話:

藍色,紅色,橙色,紫色

因此,它搜索這4個單詞的變量,並返回第一個 - 在我的例子中那麼返回的詞將是'紅'。但如果汽車是藍色的,那麼藍色的字首先會被返回,因爲這是第一個發現可能的匹配列表的字。

我該怎麼做?

+0

對不起,沒有完全得到它:如果你的字符串是'我的車是藍色的,我的鞋是藍色的',那麼你應該怎麼樣ld會被退回嗎? – 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);