从scandir中排除隐藏文件

Sin*_*ino 34 php scandir hidden-files

我使用以下代码获取目录中的图像列表:

$files = scandir($imagepath);
Run Code Online (Sandbox Code Playgroud)

$files也包括隐藏文件.我该如何排除它们?

mar*_*rio 66

在Unix上,您可以使用preg_grep过滤掉以点开头的文件名:

$files = preg_grep('/^([^.])/', scandir($imagepath));
Run Code Online (Sandbox Code Playgroud)

  • 请注意, preg_grep 返回的数组保留了输入数组的键。要重置它们,您可以将 [`array_values`](http://php.net/manual/en/function.array-values.php) 应用于结果数组。 (2认同)

Agn*_*hal 7

$files = array_diff(scandir($imagepath), array('..', '.'));
Run Code Online (Sandbox Code Playgroud)

或者

$files = array_slice(scandir($imagepath), 2);
Run Code Online (Sandbox Code Playgroud)

可能比

$files = preg_grep('/^([^.])/', scandir($imagepath));
Run Code Online (Sandbox Code Playgroud)


rob*_*lls 5

我倾向于将DirectoryIterator用于类似这样的事情,它提供了一种忽略点文件的简单方法:

$path = '/your/path';
foreach (new DirectoryIterator($path) as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $file =  $path.$fileInfo->getFilename();
}
Run Code Online (Sandbox Code Playgroud)

  • 为了明确起见,`isDot()`不会忽略以`.`开头的文件。刚在我的系统PHP 5.3.5上尝试过。 (14认同)
  • 这个答案是错误的。Unix上的“点文件”或“隐藏文件”是名称以点开头的* any *文件。但是,根据[文档](http://php.net/manual/en/directoryiterator.isdot.php),仅当文件是..或`..`时,`isDot`才匹配。快速测试确认它与大多数点文件都不匹配。 (3认同)