Can PHP's glob() be made to find files in a case insensitive manner?

前端 未结 10 1801
遥遥无期
遥遥无期 2020-11-29 08:15

I want all CSV files in a directory, so I use

glob(\'my/dir/*.CSV\')

This however doesn\'t find files with a lowercase CSV extension.

相关标签:
10条回答
  • 2020-11-29 08:23

    You could do this

    $files = glob('my/dir/*');
    
    $csvFiles =  preg_grep('/\.csv$/i', $files);
    
    0 讨论(0)
  • 2020-11-29 08:23

    glob('my/dir/*.[cC][sS][vV]') should do it. Yeah it's kind of ugly.

    0 讨论(0)
  • 2020-11-29 08:23

    Building on Alex's tip this could help generally:

    function glob_files ($d, $e)
    {
        $files = preg_grep ("/$e\$/i", glob ("$d/*"));
        sort ($files)
        return $files;
    }
    

    where $d is the directory and $e is the extension.

    0 讨论(0)
  • 2020-11-29 08:31

    You can also filter out the files after selecting all of them

    foreach(glob('my/dir/*') as $file){
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if(!in_array($ext, array('csv'))){
            continue;
        }
        ... do stuff ...
    }
    

    performance wise this might not be the best option if for example you have 1 million files that are not csv in the folder.

    0 讨论(0)
  • 2020-11-29 08:31

    This code works for me to get images only and case insensitive.

    imgage list:

    • image1.Jpg
    • image2.JPG
    • image3.jpg
    • image4.GIF
    $imageOnly = '*.{[jJ][pP][gG],[jJ][pP][eE][gG],[pP][nN][gG],[gG][iI][fF]}';
    $arr_files = (array) glob($path . $imageOnly, GLOB_BRACE);
    

    Perhaps it looks ugly but you only have to declare the $imageOnly once and can use it where needed. You can also declare $jpgOnly etc.

    I even made a function to create this pattern.

    /*--------------------------------------------------------------------------
     * create case insensitive patterns for glob or simular functions
     * ['jpg','gif'] as input
     * converted to: *.{[Jj][Pp][Gg],[Gg][Ii][Ff]}
     */
    function globCaseInsensitivePattern($arr_extensions = []) {
       $opbouw = '';
       $comma = '';
       foreach ($arr_extensions as $ext) {
           $opbouw .= $comma;
           $comma = ',';
           foreach (str_split($ext) as $letter) {
               $opbouw .= '[' . strtoupper($letter) . strtolower($letter) . ']';
           }
       }
       if ($opbouw) {
           return '*.{' . $opbouw . '}';
       }
       // if no pattern given show all
       return '*';
    } // end function
    
    $arr_extensions = [
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
    $imageOnly = globCaseInsensitivePattern($arr_extensions);
    $arr_files = (array) glob($path . $imageOnly, GLOB_BRACE);
    
    0 讨论(0)
  • 2020-11-29 08:32

    Glob patterns support character ranges:

    glob('my/dir/*.[cC][sS][vV]')
    
    0 讨论(0)
提交回复
热议问题