Checking for file-extensions in PHP with Regular expressions

前端 未结 7 2114
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 17:30

I\'m reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG.

Both capital and small letters. Those are the only files to be accepte

7条回答
  •  伪装坚强ぢ
    2020-12-28 17:55

    Is there any reason you don't want to use scandir and pathinfo?

    public function scanForFiles($path, array $exts)
    {
        $files = scanDir($path);
    
        $return = array();
    
        foreach($files as $file)
        {
            if($file != '.' && $file != '..')
            {
                if(in_array(pathinfo($file, PATHINFO_EXTENSION), $exts))) {
                    $return[] = $file;   
                }
            }
        }
    
        return $return;
    }
    

    So you could also check if the file is a directory and do a recursive call to scan that directory. I wrote the code in haste so might not be 100% correct.

提交回复
热议问题