2012-12-19 14 views

回答

0
$iHaz = FALSE; 

foreach ($arr as $item) { 
    if (preg_match('/\.txt$/', $item)) { 
     $iHaz = TRUE; 
     break; 
    } 
} 

相反到其他的答案暗示array_filter,我不回東西。我只是檢查它是否存在於數組中。此外,這個實現比array_filter更高效,因爲一旦發現它,就會跳出循環。

3

您可以遍歷數組中的項目,然後對每個項目執行正則表達式或條碼匹配。一旦你找到一個匹配,你可以返回true。

隨着strpos()

$array = array('one.php', 'two.txt'); 

$match = false; 
foreach ($array as $filename) { 
    if (strpos($filename, '.txt') !== FALSE) { 
     $match = true; 
     break; 
    } 
} 

用正則表達式:

$array = array('one.php', 'two.txt'); 

$match = false; 
foreach ($array as $filename) { 
    if (preg_match('/\.txt$/', $filename)) { 
     $match = true; 
     break; 
    } 
} 

兩者都會導致$match等同於true

+0

'substr' - >我想你的意思是'strpos'。 –

+0

德哦,謝謝你指出。XD – Maccath

4

嘗試array_filter。在回調中,檢查是否存在.txt擴展名。

如果array_filter的結果有條目(是truthy),那麼你可以得到第一個或全部。如果數組爲空,則不匹配。

1
$files = array('foo.txt', 'bar.txt', 'nope.php', ...); 

$txtFiles = array_filter($files, function ($item) { 
    return '.txt' === substr($item, -4); // assuming that your string ends with '.txt' otherwise you need something like strpos or preg_match 
}); 

var_dump($txtFiles); // >> Array ([0] => 'foo.txt', [1] => 'bar.txt') 

array_filter函數在數組中循環並將值傳遞給回調函數。如果回調函數返回true,它將保持該值,否則它將從數組中移除該值。在回調中傳遞所有項目後,返回結果數組。


噢,你只是想知道.txt是否在數組中。其他一些建議:

$match = false; 

array_map(function ($item) use ($match) { 
    if ('.txt' === substr($match, -4)) { 
     $match = true; 
    } 
}, $filesArray); 
$match = false; 
if (false === strpos(implode(' ', $filesArray), '.txt')) { 
    $match = true; 
} 
+0

@danronmoon謝謝,我剛剛編輯它。 (起初我以爲我會用'array_map'解決這個問題,它有'callback,input'命令...) –

0

既然你正在處理的文件,你應該使用array_filterpathinfo

$files = array_filter(array("a.php","b.txt","z.ftxt"), function ($item) { 
    return pathinfo($item, PATHINFO_EXTENSION) === "txt"; 
}); 

var_dump($files); // b.txt 
0

使用array_filter過濾您的陣列結果基於文件擴展名:

// Our array to be filtered 
$files = array("puppies.txt", "kittens.pdf", "turtles.txt"); 

// array_filter takes an array, and a callable function 
$result = array_filter($files, function ($value) { 
    // Function is called once per array value 
    // Return true to keep item, false to filter out of results 
    return preg_match("/\.txt$/", $value); 
}); 

// Output filtered values 
var_dump($result); 

導致以下:

array(2) { 
    [0]=> string(11) "puppies.txt" 
    [2]=> string(11) "turtles.txt" 
} 

執行它:http://goo.gl/F3oJr