How to use RegexIterator in PHP?


Regular expression

$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;
}

Using filters

A base class holds the regex that needs to be used with the filter.

classes which will extend this one. The RecursiveRegexIterator is extended.

abstract class FilesystemRegexFilter extends RecursiveRegexIterator {
   protected $regex;
   public function __construct(RecursiveIterator $it, $regex) {
      $this->regex = $regex;
      parent::__construct($it, $regex);
   }
}

They are basic filters and work with the file and directory name respectively.

class FilenameFilter extends FilesystemRegexFilter {
   // Filter files with the help of regex
   public function accept() {
      return ( ! $this->isFile() || preg_match($this->regex, $this->getFilename()));
   }
}
class DirnameFilter extends FilesystemRegexFilter {
   // Filter directories with the help of regex
   public function accept() {
      return ( ! $this->isDir() || preg_match($this->regex, $this->getFilename()));
   }
}

The below code iterates recursively over the directory contents. The trash folders are filtered out and only PHP and HTML files are retained.

$directory = new RecursiveDirectoryIterator(__DIR__);

// Filter out ".Trash*" folders
$filter = new DirnameFilter($directory, '/^(?!\.Trash)/');

// Filter PHP/HTML files
$filter = new FilenameFilter($filter, '/\.(?:php|html)$/');

foreach(new RecursiveIteratorIterator($filter) as $file) {
   echo $file . PHP_EOL;
}

Scanning up to 2 levels deep using the above code

$files = new RecursiveIteratorIterator($filter);
$files->setMaxDepth(1); // Two levels, the parameter is zero-based.
foreach($files as $file) {
   echo $file . PHP_EOL;
}

Updated on: 07-Apr-2020

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements