2012-01-17 149 views
3

我有一個字符串,如abcdefg123hijklm。我也有一個包含幾個字符串的數組。現在我想檢查我的abcdefg123hijklm並查看是否在abcdefg123hijklm之內。我怎樣才能做到這一點?我猜in_array()不會工作?將字符串與PHP中的數組進行比較?

謝謝?

+0

一個字preg_grep() – ArtisticPhoenix 2014-07-10 15:40:10

回答

12

所以,你想檢查該特定字符串(讓我們稱之爲$searchstring)的任何子字符串是否在數組中? 如果是這樣,您將需要迭代這個數組並檢查子:

foreach($array as $string) 
{ 
    if(strpos($searchstring, $string) !== false) 
    { 
    echo 'yes its in here'; 
    break; 
    } 
} 

參見:http://php.net/manual/en/function.strpos.php

如果你想檢查字符串的特定部分是你需要在數組中使用substr()來分隔該部分字符串,然後使用in_array()來查找它。

http://php.net/manual/en/function.substr.php

+2

我會把'echo'部分放在一個代碼塊(大括號)中並在結束大括號之前添加一個「break」 t - 當您只需要知道至少有一個字符串是否匹配時,可以幫助提高性能。 – Christian 2012-01-17 09:17:45

+2

^確認和實施:) – bardiir 2012-01-17 09:25:02

6

另一種選擇是使用正則表達式和破滅,就像這樣:

if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches)) 
    echo("Yes, the string '{$matches[0]}' was found in the search string."); 
else 
    echo("None of the strings in the array were found in the search string."); 

這有點更少的代碼,我希望它是大型搜索字符串或更有效數組,因爲搜索字符串只需要解析一次,而不是數組的每個元素一次。 (雖然你的確添加了implode的開銷。)

其中一個缺點是它不會返回匹配字符串的數組索引,所以如果需要的話,循環可能是更好的選擇。但是,你也可以用代碼中找到它上面,然後

$match_index = array_search($matches[0], $array); 

編輯:請注意,這是假定你知道你的字符串是不會包含正則表達式特殊字符。對於像你的例子那樣純粹的字母數字字符串,這將是真實的,但是如果你要有更復雜的字符串,你將不得不先逃脫它們。在這種情況下,使用循環的另一種解決方案可能會更簡單。

3

您可以反向操作。假設你的字符串是$ string,而數組是$ array。

foreach ($array as $value) 
{ 
    // strpos can return 0 as a first matched position, 0 == false but !== false 
    if (strpos($string, $value) !== false) 
    { 
     echo 'Matched value is ' . $value; 
    } 
} 
+2

,不會總是工作,因爲如果在$ str的開始處找到$值strpos()將返回0,其計算結果爲false – 2013-12-12 11:01:45

相關問題