dlueth
6/27/2013 - 9:36 PM

Fetch files matching an optional regex-pattern recursively from any given directory

Fetch files matching an optional regex-pattern recursively from any given directory

getFiles($directory, $recursive = false, $pattern = NULL, $absolute = false) {
  $return    = array();
	$iterator  = ($recursive === false) ? new \FilesystemIterator($directory, \FilesystemIterator::SKIP_DOTS) : new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory), \RecursiveIteratorIterator::SELF_FIRST);
	$iterator  = ($pattern !== NULL) ? new \RegexIterator($iterator, '/' . $pattern . '/i') : $iterator;
	$directory = preg_quote($directory . '/', '/');

	foreach($iterator as $path) {
		if($path->isFile() === true) {
			$return[] = ($absolute !== false) ? $path->getPathname() : preg_replace('/^' . $directory . '/', '', $path->getPathname());
		}
	}

	sort($return);

	return $return;
}