Recursively Scan A Directory For Files With Regex Using PHP

The RecursiveIteratorIterator object is built into PHP as part of the SPL package. This object accepts a RecursiveDirectoryIterator object which we set with the starting point of the iterator.

We then pass this iterator to a RegexIterator object, which allows using regular expressions to filter the files found by a regular expression. This results in an array that contains all of the results we found.

The following will scan all directories inside the "web" directory for files that have the extension "yml", which are yaml files.

$directory = 'web';

$recursiveDirectoryIterator = new RecursiveDirectoryIterator($directory);
$iterator = new RecursiveIteratorIterator($recursiveDirectoryIterator, RecursiveIteratorIterator::SELF_FIRST);
$items = new RegexIterator($iterator, '/^.+\.yml$/i', RecursiveRegexIterator::GET_MATCH);

if ($items as $name => $item) {
   // $item[0] contains the path.
}

I used this technique to find yaml files in a highly nested directory structure containing about 300 files and this took less than a second to complete.

Add new comment

The content of this field is kept private and will not be shown publicly.