Can PHP's glob() be made to find files in a case insensitive manner?
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()
?
Glob patterns support character ranges:
glob('my/dir/*.[cC][sS][vV]')
You could do this
$files = glob('my/dir/*');
$csvFiles = preg_grep('/\.csv$/i', $files);
glob('my/dir/*.[cC][sS][vV]')
should do it. Yeah it's kind of ugly.
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.
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);