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

前端 未结 10 1923
遥遥无期
遥遥无期 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: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);
    

提交回复
热议问题