$directory = new RecursiveDirectoryIterator(__DIR__); $flattened = new RecursiveIteratorIterator($directory); // Make sure the path does not contain "/.Trash*" folders and ends eith a .php or .html file $files = new RegexIterator($flattened, '#^(?:[A-Z]:)?(?:/(?!\.Trash)[^/]+)+/[^/]+\.(?:php|html)$#Di'); foreach($files as $file) { echo $file . PHP_EOL; }
基类包含需要与过滤器一起使用的正则表达式。
类将扩展这一类。RecursiveRegexIterator已扩展。
abstract class FilesystemRegexFilter extends RecursiveRegexIterator { protected $regex; public function __construct(RecursiveIterator $it, $regex) { $this->regex = $regex; parent::__construct($it, $regex); } }
它们是基本过滤器,分别与文件名和目录名一起使用。
class FilenameFilter extends FilesystemRegexFilter { //借助正则表达式过滤文件 public function accept() { return ( ! $this->isFile() || preg_match($this->regex, $this->getFilename())); } } class DirnameFilter extends FilesystemRegexFilter { //借助正则表达式过滤目录 public function accept() { return ( ! $this->isDir() || preg_match($this->regex, $this->getFilename())); } }
下面的代码递归遍历目录内容。垃圾文件夹被过滤掉,仅保留PHP和HTML文件。
$directory = new RecursiveDirectoryIterator(__DIR__); // Filter out ".Trash*" folders $filter = new DirnameFilter($directory, '/^(?!\.Trash)/'); //过滤PHP / HTML文件 $filter = new FilenameFilter($filter, '/\.(?:php|html)$/'); foreach(new RecursiveIteratorIterator($filter) as $file) { echo $file . PHP_EOL; }
$files = new RecursiveIteratorIterator($filter); $files->setMaxDepth(1); // Two levels, the parameter is zero-based. foreach($files as $file) { echo $file . PHP_EOL; }