Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude file types from Directory Iterator loop

Simple directory iterator that is recursive and shows all files and directories/sub-directories.

I don't see any built in function to exclude certain file types, for instance in the following example I do not want to output any image related files such as .jpg, .png, etc. I know there are several methods of doing this , looking for advice on which would be best.

$scan_it = new RecursiveDirectoryIterator("/example_dir");

 foreach(new RecursiveIteratorIterator($scan_it) as $file) {

  echo $file;
  }
like image 892
Wyck Avatar asked Nov 29 '22 04:11

Wyck


2 Answers

Update: Ok, so I'm an idiot. PHP has a builtin for this: pathinfo()

Try this:

$filetypes = array("jpg", "png");
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array(strtolower($filetype), $filetypes)) {
  echo $file;
}

Original Answer:

Why not just run substr() on the filename and see if it matches the extension of the file type you want to exclude:

$scan_it = new RecursiveDirectoryIterator("/example_dir");

foreach(new RecursiveIteratorIterator($scan_it) as $file) {
  if (strtolower(substr($file, -4)) != ".jpg" && 
      strtolower(substr($file, -4)) != ".jpg") {
    echo $file;
  }
}

You could make it easier by using regular expressions:

if (!preg_match("/\.(jpg|png)*$/i", $file, $matches)) {
   echo $file;
}

You could even use an array to keep track of your file types:

$filetypes = array("jpg", "png");
if (!preg_match("/\.(" . implode("|", $filetypes) . ")*$/i", $file, $matches)) {
   echo $file;
}
like image 166
AgentConundrum Avatar answered Dec 04 '22 09:12

AgentConundrum


From PHP 5.4 can use \RecursiveCallbackFilterIterator

$iterator = new \RecursiveDirectoryIterator(getcwd(), \RecursiveDirectoryIterator::SKIP_DOTS);

$iterator = new \RecursiveCallbackFilterIterator(
  $iterator,
  function ($item) {
    return $item->getExtension() === 'php' ? true : false;
  }
);

Iterator now will contains only PHP files.

 foreach($iterator as $file) {
   echo $file;
 }
like image 38
OzzyCzech Avatar answered Dec 04 '22 10:12

OzzyCzech