【问题标题】:how to exclude a certain folder when using scandir in php在php中使用scandir时如何排除某个文件夹
【发布时间】:2019-02-01 20:58:23
【问题描述】:

我正在使用 scandir 列出目录中的所有文件。但是./../tmp文件夹应该有一个例外。

我已经有了这个来排除点和双点:

$files = preg_grep('/^([^.])/', scandir($dir));

如何添加tmp 文件夹? (文件夹名称为 tmp)

【问题讨论】:

  • 顺便说一句:您使用的代码将排除 any 名称以点开头的文件或目录。这可能是也可能不是您真正想要的。
  • 我同意!但不允许以点开头的名称。它在输入中被过滤

标签: php scandir preg-grep


【解决方案1】:

我会选择这个解决方案,因为@duskwuff 已经提到,您当前的代码排除了所有以. 开头的文件

$files = array_diff( scandir($dir), array(".", "..", "tmp") );

【讨论】:

  • 我同意!这是更好的方法。工作正常!
【解决方案2】:

试试:

   $toRemove = array('.','..','tmp'); 

   $cdir = scandir($dir);
   
   $result = array_diff($cdir, $toRemove);

preg_grep简单

【讨论】:

    【解决方案3】:

    因为它是一个正则表达式,你可以尝试看看negative lookahead

    $files = preg_grep('/^(?!tmp|\.{1,2})$/', scandir($dir));
    

    【讨论】:

      【解决方案4】:

      如果你想坚持使用正则表达式,我会做类似的事情

      $files = preg_grep('/^(?!tmp|(?!([^.]))).*/', scandir($dir));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 1970-01-01
        相关资源
        最近更新 更多