繁体   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