48

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.

I could use

glob('my/dir/*.{CSV,csv}', GLOB_BRACE);

But is there a way to allow all mixed case versions? Or is this just a limitation of glob() ?

alex
  • 479,566
  • 201
  • 878
  • 984
  • Just a note that `glob()` is actually case insensitive in Windows (and possibly other insensitive file systems). – Simon East Dec 15 '14 at 00:31
  • 1
    Thats not true. `glob("*.CSV")` will only find uppercase files, while `glob("*.csv")` will only find lowercase files. --- tested in windows7 with php 5.3.8 – Radon8472 Sep 03 '15 at 09:26

11 Answers11

67

Glob patterns support character ranges:

glob('my/dir/*.[cC][sS][vV]')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    But won't it also match any file that ends in ".Csv" or ".CsV"? But that's a sidepoint: what I'm looking for is a pattern that will match all image files in a case insensitive way (jpg, JPG, png, PNG, etc.). – JohnK Jul 31 '12 at 09:14
  • 4
    @JohnK: "But is there a way to allow all mixed case versions?" – Ignacio Vazquez-Abrams Jul 31 '12 at 09:43
44

You could do this

$files = glob('my/dir/*');

$csvFiles =  preg_grep('/\.csv$/i', $files);
alex
  • 479,566
  • 201
  • 878
  • 984
7

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

intuited
  • 23,174
  • 7
  • 66
  • 88
2

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.

Timo Huovinen
  • 53,325
  • 33
  • 152
  • 143
2

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);
Henry
  • 1,242
  • 1
  • 12
  • 10
0

You can write your own case insensitive glob. This is from a personal web library I write:

/** PHP has no case insensitive globbing
 * so we have to build our own.
 *
 * $base will be the initial part of the path which doesn't need case insensitive
 * globbing.
 * Suffix is similar - it will not be made insensitive
 * Make good use of $base and $suffix to keep $pat simple and fast in use.
 */
    function ciGlob($pat, $base = '', $suffix = '')
    {
        $p = $base;
        for($x=0; $x<strlen($pat); $x++)
        {
            $c = substr($pat, $x, 1);
            if( preg_match("/[^A-Za-z]/", $c) )
            {
                $p .= $c;
                continue;
            }
            $a = strtolower($c);
            $b = strtoupper($c);
            $p .= "[{$a}{$b}]";
        }
        $p .= $suffix;
        return glob($p);
    }
Oli Comber
  • 311
  • 2
  • 11
0

I heard about a function that can be used like this: Try if that works for you!

<?php
$pattern = sql_regcase("*.txt");
glob($pattern);
?>
Jerry
  • 11
0

Came to this link for glob with multiple files. Although it doesn't help with OP, it may help others who end up here.

$file_type = 'csv,jpeg,gif,png,jpg';
$i = '0';
foreach(explode(",",$file_type) as $row){
    if ($i == '0') {
        $file_types = $row.','.strtoupper($row);
    } else {
        $file_types .= ','.$row.','.strtoupper($row);
    }
    $i++;
}

$files = glob($dir."*.{".$image_types."}",GLOB_BRACE);
Stphane
  • 3,368
  • 5
  • 32
  • 47
user3058870
  • 81
  • 1
  • 2
  • 8
0

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.

ysf
  • 4,634
  • 3
  • 27
  • 29
0

Adding to Ignacio answer, if you want to use a case insensible variable instead, you can do it by splitting the variable into bytes and preparing char ranges automatically:

$dir = "my/dir/*";
$var = ".cSv"; // example

$var_array = str_split($var); // split into bytes
$case_insensitive_var = '';
foreach($var_array as $var_byte){
    $case_insensitive_var .= '['.strtolower($var_byte).strtoupper($var_byte).']';
}

$dirs = glob($dir.$case_insensitive_var, GLOB_BRACE);

Just change $dir and $var and you're ready to go.

Simon
  • 1,314
  • 4
  • 14
  • 26
-1

To make it work with all extensions use:

$extension = 'some_extension';
glob('my/dir/*.preg_replace('/(\w)/e', "'['.strtoupper($1).strtolower($1).']'", $extension));
Dan Bray
  • 7,242
  • 3
  • 52
  • 70
  • 3
    i can't speak for whomever down-voted you, but a couple of (hopefully helpful) points: (1) your path string is missing the closing `'`, and (2) the PCRE `e` (eval) flag is deprecated as of PHP 5.5 and removed in 7, both of which are older than this answer. Its usage is discouraged. – cautionbug Jan 10 '18 at 04:09
  • `preg_replace()` is needlessly used. You could `explode()`, `map()`, return the case variants and then `join()`. – alex Mar 05 '18 at 11:33