【问题标题】:Find files with a given extension in a directory tree在目录树中查找具有给定扩展名的文件
【发布时间】:2012-04-02 15:34:00
【问题描述】:

我有一个文件夹,其中有一些文件和子文件夹。我需要返回具有给定扩展名的文件名或相对地址(如果文件位于子文件夹中),例如 .html

例如这是给定文件夹的结构:

  • /text/something.ncx
  • /text/123.html
  • content.opf
  • toc.ncx
  • Flow_0.html
  • Flow_1.html
  • Flow_2.html

所以代码应该返回这个(最好是在一个数组中):

  • text/123.html
  • Flow_0.html
  • Flow_1.html
  • Flow_2.html

它只是提取带有.html 扩展名的名称,但我真的不知道如何解决这个问题。

【问题讨论】:

标签: php filenames


【解决方案1】:

您可以使用RecursiveDirectoryIterator 递归地获取所有 个文件,然后使用RegexIterator 过滤结果以仅迭代*.html 文件。要获取相对地址,可以使用RecursiveDirectoryIterator::getSubPathname()

$directory  = '../path/to/your/folder';
$all_files  = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
$html_files = new RegexIterator($all_files, '/\.html$/');

foreach($html_files as $file) {
    echo $html_files->getSubPathname(), PHP_EOL;
}

如果您确实需要和数组(使用您通常不需要的可迭代对象),您可以轻松地在 foreach 而不是 echo-ing 每个子路径中构建一个。

【讨论】:

    【解决方案2】:

    列出文件夹中的文件(将 $directory 值更改为您的首选目录名,@$files 将您的扩展名从 .txt 更改为首选。

    $directory = "../images/team/harry/";
    
    
    $files = glob($directory . "*.txt");
    
    
    foreach($files as $file)
    {
    echo $file;
    }
    

    【讨论】:

    • 这不会递归到子目录中。
    【解决方案3】:

    您可以使用glob function

    glob('*.html')
    

    【讨论】:

      【解决方案4】:

      你可以简单地使用它

      <h1>
      
      $Dir = 'you dir/';
      $File = scandir($Dir);
      $Type = pathinfo($File[$x],PATHINFO_EXTENSION);
      if (strtolower($Type) === 'html'){
               echo $File;
      }
      <H2>
      

      【讨论】:

      • 请解释您对 OP 的回答,代码转储没有帮助
      猜你喜欢
      • 2019-03-07
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      相关资源
      最近更新 更多