如何使RecursiveDirectoryIterator排除隐藏文件夹

时间:2014-11-12 14:42:05

标签: php

我有一个像这样的recursiveDirectoryIterator:

$theme_iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($theme_folder_path)
);
foreach ($theme_iterator as $file_object) {
   // Stuff
}

问题是它迭代到.svn隐藏文件夹。我该如何防止这种情况?

编辑:

我不能在foreach中添加这样的内容,因为隐藏文件夹中的文件已经在数组中已经存在,并且它们并非全部隐藏。

if (strpos($file_object, ".") ===0) {
    continue;
}

4 个答案:

答案 0 :(得分:5)

<?php
class RecursiveDotFilterIterator extends  RecursiveFilterIterator
{
    public function accept()
    {
        return '.' !== substr($this->current()->getFilename(), 0, 1);
    }
}

$iterator = new RecursiveIteratorIterator(
    new RecursiveDotFilterIterator(
        new RecursiveDirectoryIterator('.')
    )
);
foreach ($iterator as $x) {
    //do stuff
}

答案 1 :(得分:3)

设置flag RecursiveDirectoryIterator::SKIP_DOTS以排除文件:

答案 2 :(得分:0)

这是使用RecursiveCallbackFilterIterator的另一种方法:

<?php

$f_filter = function ($o_info) {
   if ($o_info->isFile()) {
      return true;
   }
   $s_file = $o_info->getFilename();
   if (strpos($s_file, '.') === 0) {
      return false;
   }
   return true;
};

$o_dir = new RecursiveDirectoryIterator('.');
$o_filter = new RecursiveCallbackFilterIterator($o_dir, $f_filter);
$o_iter = new RecursiveIteratorIterator($o_filter);

foreach ($o_iter as $o_info) {
   echo $o_info->getPathname(), "\n";
}

https://php.net/class.recursivecallbackfilteriterator

答案 3 :(得分:-1)

如果你想在一行中做到这一点:

$iterator = new RecursiveDirectoryIterator($path_directory, RecursiveDirectoryIterator::SKIP_DOTS);