簡體   English   中英

計算目錄中的文件,同時使用PHP按目錄和子目錄排除其他文件

[英]Count files in a directory while excluding others by directory and subdirectories using PHP

我使用在SO上找到的函數實現了文件計數代碼: https : //stackoverflow.com/a/640944/2554788

該功能因此去:

function getFileCount($path) {
    $size = 0;
    $ignore = array('.','..','cgi-bin','.DS_Store');
    $files = scandir($path);
    foreach($files as $t) {
        if(in_array($t, $ignore)) continue;
        if (is_dir(rtrim($path, '/') . '/' . $t)) {
            $size += getFileCount(rtrim($path, '/') . '/' . $t);
        } else {
            $size++;
        }   
    }
    return $size;
}

效果很好,直到我要排除某些目錄及其所有內容 我需要通過的是:

$ignore = array('.','..','cgi-bin','.DS_Store', 'SPECIAL_DIR');

目前,此函數省略了“ SPECIAL_DIR”,但似乎計算了所有內容文件,因為它們在文本上與“ SPECIAL_DIR”不匹配!

我在這里和其他地方遇到了一些解決方案,這些解決方案旨在按路徑排除文件,但是我還沒有找到一個專注於遞歸計數文件( 不列出文件或其他內容)的解決方案。

謝謝大家

我從《 PHP手冊》中用戶提供的部分中發現了這一點。 感謝isharelife dot com dot br的carneiro

function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
         $arrayItems = array();
         $skipByExclude = false;
         $handle = opendir($directory);
         if ($handle) {
             while (false !== ($file = readdir($handle))) {
             preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
             if($exclude){
                 preg_match($exclude, $file, $skipByExclude);
             }
             if (!$skip && !$skipByExclude) {
                 if (is_dir($directory. '/' . $file)) {
                     if($recursive) {
                         $arrayItems = array_merge($arrayItems, directoryToArray($directory. '/' . $file, $recursive, $listDirs, $listFiles, $exclude));
                     }
                     if($listDirs){
                         $file = $directory . '/' . $file;
                         $arrayItems[] = $file;
                     }
                 } else {
                     if($listFiles){
                         $file = $directory . '/' . $file;
                         $arrayItems[] = $file;
                     }
                 }
             }
         }
         closedir($handle);
         }
         return $arrayItems;
  }

該函數返回完整的路徑列表。 通過傳遞給函數的正則表達式進行排除,文件計數來自返回數組的count()

這似乎可以解決問題,但是我在等待有關代碼簡潔性和性能等問題的任何替代答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM