/** * Get list of files/directories from supplied directory. * * @param array $options * 'dir' => boolean, include directory paths * 'ext' => file suffix, no full stop (period) separator should be used. * 'path' => The path to list from. If left empty it will use whatever the current working directory is. * 'regex' => Regular expressions that the full path must match to be included, * * @return array Always returns array of path-names in unix format (even on Windows). */ public static function getDirFiles(array $options = null) { $defaults = array('dir' => false, 'ext' => '', 'path' => '', 'regex' => ''); $options += $defaults; $files = array(); $iterator = new \FilesystemIterator($options['path'], \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS); foreach ($iterator as $fileinfo) { $file = $iterator->key(); switch (true) { case !$options['dir'] && $fileinfo->isDir(): break; case !empty($options['ext']) && $fileinfo->getExtension() != $options['ext']: break; case empty($options['regex']) || !preg_match($options['regex'], $file): break; default: $files[] = $file; } } return $files; }
<?php $sample_dir = __DIR__ . '/../../sample_dir'; $iterator = new FilesystemIterator($sample_dir, FilesystemIterator::KEY_AS_FILENAME); $a = $iterator->key(); $iterator->next(); $b = $iterator->key(); $iterator->rewind(); $c = $iterator->key(); var_dump($a == $b); var_dump($a == $c);
/** * Get list of files/directories from supplied directory. * * @param array $options * 'dir' => boolean, include directory paths * 'ext' => file suffix, no full stop (period) separator should be used. * 'path' => The path to list from. If left empty it will use whatever the current working directory is. * 'regex' => Regular expressions that the full path must match to be included, * * @return array Always returns array of path-names in unix format (even on Windows). */ public static function getDirFiles(array $options = null) { $defaults = ['dir' => false, 'ext' => '', 'path' => '', 'regex' => '']; $options += $defaults; // Replace windows style path separators with unix style. $iterator = new \FilesystemIterator(str_replace('\\', '/', $options['path']), \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS); $files = []; foreach ($iterator as $fileInfo) { $file = $iterator->key(); switch (true) { case !$options['dir'] && $fileInfo->isDir(): break; case !empty($options['ext']) && $fileInfo->getExtension() != $options['ext']: break; case empty($options['regex']) || !preg_match($options['regex'], $file): break; default: $files[] = $file; } } return $files; }
<?php $sample_dir = __DIR__ . '/../../sample_dir'; $iterator = new FilesystemIterator($sample_dir, FilesystemIterator::KEY_AS_FILENAME); $ret = array(); foreach ($iterator as $fileinfo) { $ret[] = $iterator->key(); } asort($ret); var_dump(array_values($ret));