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

发布于 2024-08-26 14:12:26 字数 258 浏览 12 评论 0原文

我希望目录中的所有 CSV 文件,因此我使用

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

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

可以使用

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

但是有没有办法允许所有混合大小写版本?或者这只是 glob() 的限制?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

香草可樂 2024-09-02 14:12:27

要使其与所有扩展一起使用,请使用:

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

To make it work with all extensions use:

$extension = 'some_extension';
glob('my/dir/*.preg_replace('/(\w)/e', "'['.strtoupper($1).strtolower($1).']'", $extension));
柏拉图鍀咏恒 2024-09-02 14:12:26

Glob 模式支持字符范围:

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

Glob patterns support character ranges:

glob('my/dir/*.[cC][sS][vV]')
口干舌燥 2024-09-02 14:12:26

你可以这样做

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

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

You could do this

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

$csvFiles =  preg_grep('/\.csv$/i', $files);
翻了热茶 2024-09-02 14:12:26

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

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

小瓶盖 2024-09-02 14:12:26

您还可以在选择所有文件后过滤掉这些文件,

foreach(glob('my/dir/*') as $file){
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    if(!in_array($ext, array('csv'))){
        continue;
    }
    ... do stuff ...
}

从性能角度考虑,这可能不是最佳选择,例如,如果文件夹中有 100 万个非 csv 文件。

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.

太傻旳人生 2024-09-02 14:12:26

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

图像列表:

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

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

我什至制作了一个函数来创建此模式。

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

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);
少钕鈤記 2024-09-02 14:12:26

您可以编写自己的不区分大小写的 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);
    }

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);
    }
深白境迁sunset 2024-09-02 14:12:26

我听说有一个函数可以这样使用:
尝试一下是否适合您!

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

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

<?php
$pattern = sql_regcase("*.txt");
glob($pattern);
?>
墨洒年华 2024-09-02 14:12:26

来到此链接获取具有多个文件的 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);

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);
浅笑轻吟梦一曲 2024-09-02 14:12:26

根据 Alex 的提示,这通常会有所帮助:

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

其中 $d 是目录,$e 是扩展名。

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.

暮年慕年 2024-09-02 14:12:26

添加到 Ignacio 答案中,如果您想使用不区分大小写的变量,您可以通过将变量拆分为字节并自动准备字符范围来实现:

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

只需更改 $dir 和 $var 就可以了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文