可以使 PHP 的 glob() 以不区分大小写的方式查找文件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2520612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:48:09  来源:igfitidea点击:

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

phpcase-insensitiveglob

提问by alex

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

我想要一个目录中的所有 CSV 文件,所以我使用

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

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

但是,这不会找到带有小写 CSV 扩展名的文件。

I coulduse

可以

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()

回答by Ignacio Vazquez-Abrams

Glob patterns support character ranges:

Glob 模式支持字符范围:

glob('my/dir/*.[cC][sS][vV]')

回答by alex

You could do this

你可以这样做

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

$csvFiles =  preg_grep('/\.csv$/i', $files);

回答by intuited

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

glob('my/dir/*.[cC][sS][vV]')应该这样做。是的,有点丑。

回答by Timo Huovinen

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.

在性能方面,这可能不是最佳选择,例如,如果文件夹中有 100 万个不是 csv 的文件。

回答by Jerry

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

我听说过一个可以这样使用的函数:试试它是否适合你!

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

回答by user3058870

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

来到这个带有多个文件的 glob 的链接。虽然它对 OP 没有帮助,但它可能会帮助到这里的其他人。

$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);

回答by Henry

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

此代码适用于我只获取图像且不区分大小写。

imgage list:

图片列表:

  • image1.Jpg
  • image2.JPG
  • image3.jpg
  • image4.GIF
  • 图片1.Jpg
  • 图片2.JPG
  • 图片3.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.

也许它看起来很丑,但你只需要声明一次 $imageOnly 就可以在需要的地方使用它。您还可以声明 $jpgOnly 等。

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);

回答by Lee Traynor

Building on Alex's tip this could help generally:

基于 Alex 的提示,这通常会有所帮助:

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

where $dis the directory and $eis the extension.

哪里$d是目录,$e是扩展名。

回答by Oli Comber

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

您可以编写自己的不区分大小写的 glob。这是来自我写的个人网络图书馆:

/** 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);
    }

回答by Dan Bray

To make it work with all extensions use:

要使其适用于所有扩展,请使用:

$extension = 'some_extension';
glob('my/dir/*.preg_replace('/(\w)/e', "'['.strtoupper().strtolower().']'", $extension));