在目录树中查找具有给定扩展名的文件 [英] Find files with a given extension in a directory tree
问题描述
我有一个文件夹,其中有一些文件和子文件夹.我需要返回具有给定扩展名的文件名或相对地址(如果文件位于子文件夹中),例如 .html
.
I have a folder in which I have some files and sub-folders. I need to return the names of the files or relative address (if the file is in sub-folder) that have a given extension, for example .html
.
例如,这是给定文件夹的结构:
For example this is structure of given folder:
- /text/something.ncx
- /text/123.html
- content.opf
- toc.ncx
- Flow_0.html
- Flow_1.html
- Flow_2.html
因此,代码应返回此值(理想情况下是在数组中):
So the code should return this (in an array ideally):
- text/123.html
- Flow_0.html
- Flow_1.html
- Flow_2.html
它只是提取扩展名为 .html
的名称,但我真的不知道如何解决这个问题.
It's just pulling out names with .html
extension, but I really don't how to solve this.
推荐答案
您可以使用 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.
这篇关于在目录树中查找具有给定扩展名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!