我製作了這個函式,可以透過副檔名或檔名中出現的字串來搜尋和/或顯示檔案。當然,歡迎任何意見或改進。我很快就會更新這個函式。
用法:list_files([字串], [字串], [整數 1 | 0], [整數 1 | 0]);
搜尋副檔名:list_files([字串], [字串], [0], [整數 1 | 0]);
傳回陣列:$myArray = list_files([字串], [字串], [0], [0]);
顯示結果:list_files([字串], [字串], [0], [1]);
搜尋出現的字串:list_files([字串], [字串], [1], [整數 1 | 0]);
傳回陣列:$myArray = list_files([字串], [字串], [1], [0]);
顯示結果:list_files([字串], [字串], [1], [1]);
<?php
function list_files($directory, $stringSearch, $searchHandler, $outputHandler) {
$errorHandler = false;
$result = array();
if (! $directoryHandler = @opendir ($directory)) {
echo ("<pre>\n錯誤:目錄 \"$directory\" 不存在!\n</pre>\n");
return $errorHandler = true;
}
if ($searchHandler === 0) {
while (false !== ($fileName = @readdir ($directoryHandler))) {
if(@substr ($fileName, - @strlen ($stringSearch)) === $stringSearch) {
@array_push ($result, $fileName);
}
}
}
if ($searchHandler === 1) {
while(false !== ($fileName = @readdir ($directoryHandler))) {
if(@substr_count ($fileName, $stringSearch) > 0) {
@array_push ($result, $fileName);
}
}
}
if (($errorHandler === true) && (@count ($result) === 0)) {
echo ("<pre>\n錯誤:找不到檔案類型 \"$fileExtension\" !\n</pre>\n");
}
else {
sort ($result);
if ($outputHandler === 0) {
return $result;
}
if ($outputHandler === 1) {
echo ("<pre>\n");
print_r ($result);
echo ("</pre>\n");
}
}
}
?>