回答
$iHaz = FALSE;
foreach ($arr as $item) {
if (preg_match('/\.txt$/', $item)) {
$iHaz = TRUE;
break;
}
}
相反到其他的答案暗示array_filter
,我不回東西。我只是檢查它是否存在於數組中。此外,這個實現比array_filter
更高效,因爲一旦發現它,就會跳出循環。
您可以遍歷數組中的項目,然後對每個項目執行正則表達式或條碼匹配。一旦你找到一個匹配,你可以返回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
。
'substr' - >我想你的意思是'strpos'。 –
德哦,謝謝你指出。XD – Maccath
嘗試array_filter
。在回調中,檢查是否存在.txt
擴展名。
如果array_filter
的結果有條目(是truthy),那麼你可以得到第一個或全部。如果數組爲空,則不匹配。
$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;
}
@danronmoon謝謝,我剛剛編輯它。 (起初我以爲我會用'array_map'解決這個問題,它有'callback,input'命令...) –
既然你正在處理的文件,你應該使用array_filter
和pathinfo
$files = array_filter(array("a.php","b.txt","z.ftxt"), function ($item) {
return pathinfo($item, PATHINFO_EXTENSION) === "txt";
});
var_dump($files); // b.txt
使用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"
}
- 1. Elasticsearch - 搜索數組中的值的一部分的記錄
- 2. 在數組中搜索一個值,但只打印第一個實例[更新]
- 3. 搜索字的一部分
- 4. 只有一部分主鍵高效搜索?
- 5. Solr 3.5只搜索索引文件的一部分
- 6. 在多維數組中搜索任意鍵的部分值
- 7. 彈性搜索分組唯一值
- 8. 搜索數組值
- 9. 搜索數組值
- 10. 搜索數組的一部分的多個線程
- 11. 搜索數組中的鍵的一部分 - PHP
- 12. 索引表中只有一個部分
- 13. 只有cURL數組的特定部分
- 14. Java:如何搜索字符串的一部分數組
- 15. 如何搜索數組中的一部分字符串?
- 16. 搜索數組值的PHP
- 17. 搜索值的數組
- 18. 搜索數組的值
- 19. 搜索元組列表中的元組的一部分
- 20. 按分組計數但只檢索一列
- 21. DLL搜索路徑只是部分搜索
- 22. 只搜索python中的矩陣的一部分
- 23. 複製只能從兩維數組的一些值的部分
- 24. 索引數組的一部分
- 25. 爲什麼bash在爲數組的一部分搜索數組時返回true?
- 26. 搜索第一部分多維數組ActionScript 3
- 27. 只搜索文件名的一部分文件名已知
- 28. 子彈只搜索項目的一部分
- 29. 正則表達式只搜索字符串的一部分
- 30. 如何執行joomla搜索只有一個組件數據
'array_filter'和strstr回調例如 – Rufinus