如何从Directory Iterator循环中排除文件类型 [英] How to exclude file types from Directory Iterator loop

查看:141
本文介绍了如何从Directory Iterator循环中排除文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的目录迭代器是递归的,并显示所有文件和目录/子目录。

Simple directory iterator that is recursive and shows all files and directories/sub-directories.

我没有看到任何内置函数来排除某些文件类型,例如在以下示例中,我不想输出任何图像相关的文件,例如 .jpg .png 我知道有几种方法来做这个,寻找最好的建议。

I don't see any built in function to exclude certain file types, for instance in the following example I do not want to output any image related files such as .jpg, .png, etc. I know there are several methods of doing this , looking for advice on which would be best.

$scan_it = new RecursiveDirectoryIterator("/example_dir");

 foreach(new RecursiveIteratorIterator($scan_it) as $file) {

  echo $file;
  }


推荐答案

更新: / strong>
好​​的,所以我是个白痴。 PHP有一个内置的: pathinfo()

尝试这个:

$filetypes = array("jpg", "png");
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array(strtolower($filetype), $filetypes)) {
  echo $file;
}






为什么不在文件名上运行 substr(),看看它是否与扩展名匹配您要排除的文件类型:

Why not just run substr() on the filename and see if it matches the extension of the file type you want to exclude:

$scan_it = new RecursiveDirectoryIterator("/example_dir");

foreach(new RecursiveIteratorIterator($scan_it) as $file) {
  if (strtolower(substr($file, -4)) != ".jpg" && 
      strtolower(substr($file, -4)) != ".jpg") {
    echo $file;
  }
}

您可以使用正则表达式更容易: / p>

You could make it easier by using regular expressions:

if (!preg_match("/\.(jpg|png)*$/i", $file, $matches)) {
   echo $file;
}

甚至可以使用一个数组来跟踪你的文件类型: p>

You could even use an array to keep track of your file types:

$filetypes = array("jpg", "png");
if (!preg_match("/\.(" . implode("|", $filetypes) . ")*$/i", $file, $matches)) {
   echo $file;
}

这篇关于如何从Directory Iterator循环中排除文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆