简体   繁体   中英

Scan directory for files with specific extensions recursively

I am trying to find all files in folder and subfolders with specific extensions.

 $dir = new RecursiveDirectoryIterator($directory);
 $iter = new RecursiveIteratorIterator($dir);
 $files = new RegexIterator($iter, '/.*\.(src|in|out|rc)$/i', RecursiveRegexIterator::GET_MATCH);

My output should look like this var_dump()

  array(105) {
  [2]=>
  string(6) "00.out"
  [3]=>
  string(6) "00.src"
  [4]=>
  string(6) "01.out"...
}

Actual result

object(RegexIterator)#4 (1) {
  ["replacement"]=>
  NULL
}

Where am I doing mistake? Thanks for help!

It looks like the PHP glob() function does what you want:

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

And here is a nifty function by agd243 that uses glob() to find all files by extension an return it as an array:

function findFiles($directory, $extensions = array()) {
    function glob_recursive($directory, &$directories = array()) {
        foreach(glob($directory, GLOB_ONLYDIR | GLOB_NOSORT) as $folder) {
            $directories[] = $folder;
            glob_recursive("{$folder}/*", $directories);
        }
    }
    glob_recursive($directory, $directories);
    $files = array ();
    foreach($directories as $directory) {
        foreach($extensions as $extension) {
            foreach(glob("{$directory}/*.{$extension}") as $file) {
                $files[$extension][] = $file;
            }
        }
    }
    return $files;
}
var_dump(findFiles("C:\\baseFolder", array (

    "src",
    "in",
    "out",
    "rc"
)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM