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


Find files with a given extension in a directory tree

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

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

  • /text/mething.ncx
  • /text/123.html
  • 内容.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中构建每个子路径。

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

$directory = "../images/team/harry/";

$files = glob($directory . "*.txt");

foreach($files as $file)
{
echo $file;
}

您可以使用glob函数

glob('*.html')

您可以简单地使用这个

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