2014-01-27 22 views
0

如何檢查字符串是否包含數組的成員,並返回相關成員的索引(整數)?PHP中的字符串包含哪個數組成員?

比方說,我的字符串是這樣的:

$string1 = "stackoverflow.com"; 
$string2 = "superuser.com"; 
$r = array("queue" , "stack" , "heap"); 

get_index($string1 , $r); // returns 1 
get_index($string2 , $r); // returns -1 since string2 does not contain any element of array 

我怎麼能寫這個功能在一個優雅的(短)和有效的方式?

我發現了一個函數(表達式?)來檢查,如果字符串中包含的陣列的構件:

(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array))) 

但是這是一個布爾值。 count()函數是否在本聲明中返回我想要的內容?

感謝您的幫助!

+0

僅供參考,您的一個線是不是最好的代碼。一個爆炸,轉換和相交是一個大的字符串/數組上的「重」行爲,可以做得更容易:) – Martijn

回答

0
function get_index($str, $arr){ 
    foreach($arr as $key => $val){ 
    if(strpos($str, $val) !== false) 
    return $key; 
    } 
return -1; 
} 

演示:https://eval.in/95398

+0

這隻返回數組的第一個鍵。 TS希望(如果我理解正確)匹配元素的數量,而不僅僅是第一個密鑰。除此之外,請在我的代碼中查看'break;'。 – Martijn

+0

我確實需要索引。對不起,如果我措辭嚴重的問題。這個答案正是我正在尋找的。儘管我沒有測試其他人,但感謝所有的答案! – jeff

+0

這將只返回FIRST鍵。如果你想要所有的鍵,你可以使用我的函數做一個小改動 – Martijn

0

這會發現你的數組中的匹配元素的數量,如果你希望所有匹配的密鑰,使用註釋行來代替:

function findMatchingItems($needle, $haystack){ 
    $foundItems = 0; // start counter 
    // $foundItems = array(); // start array to save ALL keys 
    foreach($haystack as $key=>$value){ // start to loop through all items 
     if(strpos($value, $needle)!==false){ 
      ++$foundItems; // if found, increase counter 
      // $foundItems[] = $key; // Add the key to the array 
     } 
    } 
    return $foundItems; // return found items 
} 

findMatchingItems($string1 , $r); 
findMatchingItems($string2 , $r); 

如果你想返回所有匹配的鍵,只需將$foundItems更改爲數組,然後在if語句中添加鍵(切換到註釋行)。

如果你只是想知道如果事情匹配與否

function findMatchingItems($needle, $haystack){ 
    if(strpos($value, $needle)!==false){ 
     return true; 
     break; // <- This is important. This stops the loop, saving time ;) 
    } 
    return false;// failsave, if no true is returned, this will return 
} 
-1

我會做這樣的函數:

function getIndex($string, $array) { 
    $index = -1; 
    $i = 0; 
    foreach($array as $array_elem) { 
     if(str_pos($array_elem, $string) !== false) { 
      $index = $i; 
     } 
     $i++; 
    } 
    return $index; 
} 
+0

雖然這個工作,我不認爲TS意味着獲得索引,而是匹配元素的數量 – Martijn

+0

此外,你現在運行一個'$ i ++'這可能是不正確的。如果你有從A到Z的鍵,那麼鍵7將意味着什麼:)我建議'($ array爲$ key => value)'方法,並返回'$ key'。 – Martijn

+0

哈哈,另外:請看我的回答,最後一個例子,然後是'break;' – Martijn

相關問題