Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files with a given extension in a directory tree

Tags:

php

filenames

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

It's just pulling out names with .html extension, but I really don't how to solve this.

like image 569
Lukáš Jelič Avatar asked Dec 12 '25 01:12

Lukáš Jelič


1 Answers

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;
}

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.

like image 137
salathe Avatar answered Dec 14 '25 16:12

salathe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!