DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Troels has posted 3 posts at DZone. View Full User Profile

Recursively Find Files By Filename Pattern.

06.15.2007
| 40578 views |
  • submit to reddit
        Scans a directory, and all subdirectories for files, matching a regular expression. Each match is sent to the callback provided as third argument. A simple example:

function my_handler($filename) {
  echo $filename . "\n";
}
find_files('c:/', '/php$/', 'my_handler');

And the actual snippet

function find_files($path, $pattern, $callback) {
  $path = rtrim(str_replace("\\", "/", $path), '/') . '/';
  $matches = Array();
  $entries = Array();
  $dir = dir($path);
  while (false !== ($entry = $dir->read())) {
    $entries[] = $entry;
  }
  $dir->close();
  foreach ($entries as $entry) {
    $fullname = $path . $entry;
    if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
      find_files($fullname, $pattern, $callback);
    } else if (is_file($fullname) && preg_match($pattern, $entry)) {
      call_user_func($callback, $fullname);
    }
  }
}
    

Comments

Snippets Manager replied on Wed, 2010/02/17 - 7:19am

Shortest way to do the same: function find_files($path, $pattern, $callback) { $path = rtrim(str_replace("\\", "/", $path), '/') . '/*'; foreach (glob ($path) as $fullname) { if (is_dir($fullname)) { find_files($fullname, $pattern, $callback); } else if (preg_match($pattern, $fullname)) { call_user_func($callback, $fullname); } } }

Snippets Manager replied on Thu, 2010/09/23 - 11:02am

is the function just returning an array of files that match? why not use glob in the function? example: <?php function find_files($dir) { $return = array(); $glob1 = glob("$dir/*"); for($i=0;$i<=count($glob1)-1;$i++) { if(!is_dir($dir[$i])) { array_push($return, $dir[$i]); } else { $return = array_merge($return, find_files($dir[$i])); } } return $return; } ?> i dont know if thats the same thing or not, but its the concept...