php - 在目录树中查找具有给定扩展名的文件

标签 php filenames

我有一个文件夹,其中有一些文件和子文件夹。我需要返回具有给定扩展名的文件名或相对地址(如果文件位于子文件夹中),例如.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扩展名的名称,但是我真的不知道如何解决这个问题。

    最佳答案

    您可以使用 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中构建每个子路径。

    关于php - 在目录树中查找具有给定扩展名的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9748320/

    相关文章:

    php - 将 phpcs 修复程序的结果存储到文件中

    Php根据请求值更新和减去数组值

    php - 正则表达式在一场比赛中获取所有比赛

    file - 用于/f 处理带空格的文件名

    php - 使用 PHP 访问文件夹并选择文件名

    php - 使用 PHP 获取 JSON 数据

    javascript - $http get angularjs 无法传递参数?

    javascript - 如何在 JavaScript 中检查文件名是否包含子字符串?

    Python - 根据提供的模式生成文件名

    javascript - 从堆栈跟踪中获取文件名