且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-28 17:19:19

您可以使用 RecursiveDirectoryIterator 递归获取所有文件,然后使用 RegexIterator 过滤结果code> 仅遍历 *.html 文件.要获取相对地址,请 RecursiveDirectoryIterator :: getSubPathname() 可以使用.

You could use a RecursiveDirectoryIterator to get all files recursively, then filter the result with a RegexIterator to iterate over only the *.html files. To get the relative adress, RecursiveDirectoryIterator::getSubPathname() can be used.

$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 -遍历每个子路径

If you really need and array (with iterable objects you often don't), you can easily build one up in the foreach rather than echo-ing each subpath.