2010-10-01 30 views
1

這裏是我的搜索數組:搜索通過在陣列中的項目中的任何一個字符串

$aExt = array('png','jpg','gif'); 

我想通過變量來搜索:

$sIcon 

如何搜索如果變量包含使用PHP的數組中的任何內容?

這就像在倒in_array:

strstr($sIcon, $aExt) < - 可第二ARG是一個數組?

+2

你能提供一些例子嗎? 「我想給你一份禮物?」比賽?或沒有? – ircmaxell 2010-10-01 17:23:05

回答

2

可以使用的foreach遍歷數組中的元素,然後用strpos,看看,關鍵是在變量的內容:

foreach($aExt as $key) { 
    if(strpos($sIcon, $key) !== false) { 
    echo sprintf("%s is in the variable", $key); 
    } 
} 

看你的變數,我認爲你的名字試圖找出文件名的擴展名。您可以使用很容易找到一個文件的擴展名如下:

$ext = pathinfo($filename, PATHINFO_EXTENSION); 

你的情況:

$ext = pathinfo($sIcon, PATHINFO_EXTENSION); 
if(in_array($ext, $aExt)) { 
    echo "Valid icon!"; 
} 
+1

+1,建議首先抓取擴展名,然後使用'in_array()'。 – Matthew 2010-10-01 17:34:12

+0

if(file_exists($ sIconPath)){ – tmartin314 2010-10-01 17:41:47

+0

@dan感謝您的想法。我將圖像路徑傳遞給函數而不是名稱,而不是使用file_exists處理它。很棒。 – tmartin314 2010-10-01 17:43:35

相關問題