Little Code
Little Code

Reputation: 1545

Checking if parent directory is contained within file path

I am working with RecursiveIteratorIterator and as part of that I would like to exclude certain paths.

The idea I have so far (code below) works ok if I happen to specify an exact match. But I also need to match if a parent matches (i.e. /foo would match /foo/bar).

I can't quite figure out how to achieve this in a clean manner.

// for clarity: $exclDirArray normally comes from function  (function dirIterator($path,array $exclDirArray=array()), I have just split it out to make my example code simpler
$exclDirArray=array('/foo','/bar');
$files = new \RecursiveDirectoryIterator($path,\FilesystemIterator::SKIP_DOTS|\FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO);
foreach(new \RecursiveIteratorIterator($files) as $file) {
   if (!empty($exclDirArray) && \in_array($file->getPath(),$exclDirArray)) {
       echo $file->getPath().PHP_EOL;
      continue;
  }
 // more stuff goes here 
}

Upvotes: 0

Views: 36

Answers (1)

Ben Harold
Ben Harold

Reputation: 6432

You could use a RegexIterator. Something along the lines of:

$rexeg = new RegexIterator($files, '#^((?!/foo).)*$#i', RecursiveRegexIterator::GET_MATCH);

In this case, $regex should be an array of all the paths that don't include the string /foo.

Upvotes: 1

Related Questions