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.
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.
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.
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:
$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);
Glob patterns support character ranges:
glob('my/dir/*.[cC][sS][vV]')