2021-12-09

Tech Programing

程式人小天地

PHP: search recursively for specific file extensions, exclude certain directories

1 min read


Clueless PHP coder here. I have a photo library structured as follows:

DIR
  thumbnails
file1.jpeg
file1.NEF
file2.JPG
  SUBDIR
   thumbnails
  file3.jpeg
  file3.ARW
  file4.NEF

I’d like my PHP script to find all *.jpeg files in all directories, except thumbnails.

Thanks to my amazing copy-pasting skills, I came up with this:

function rsearch($dir, $pattern_array) {
  $return = array();
  $iti = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
  foreach(new RecursiveIteratorIterator($iti) as $file){
    if (in_array(strtolower(array_pop(explode('.', $file))), $pattern_array)){
                    $return[] = $file;
    }
  }
  return $return;
}

$files = rsearch("photos", array('jpeg', 'JPEG'));

It works, but it also returns result from all thumbnails subdirectories. And I can’t for the live of me figure out how to exclude them. I’d be grateful for any suggestions.

Thank you in advance!



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *