Search code examples
phpfileiteratordirectoryspl

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

Solution

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