从 php 中特定扩展名过滤的目录中获取文件的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8541180/
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-26 04:56:52  来源:igfitidea点击:

Best way to get files from a dir filtered by certain extension in php

phpfilesystems

提问by CodeCrack

Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!

可能重复:
目录中特定文件的 PHP 列表
使用 php scandir($dir) 并仅获取图像!

So right now I have a directory and I am getting a list of files

所以现在我有一个目录,我得到了一个文件列表

$dir_f = "whatever/random/";
$files = scandir($dir_f);

That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.

但是,这会检索目录中的每个文件。我将如何以最有效的方式仅检索具有特定扩展名的文件,例如 .ini。

回答by Lix

PHP has a great function to help you capture only the files you need. Its called glob()

PHP 有一个很棒的功能可以帮助您只捕获您需要的文件。它被称为glob()

glob- Find pathnames matching a pattern

glob- 查找匹配模式的路径名

Here is an example usage -

这是一个示例用法 -

$files = array();
foreach (glob("/path/to/folder/*.txt") as $file) {
  $files[] = $file;
}

Reference -

参考 -

回答by mario

If you want more than one extension searched, then preg_grep()is an alternative for filtering:

如果您想搜索多个扩展名,则preg_grep()是过滤的替代方法:

 $files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));

Though globhas a similar extra syntax. This mostly makes sense if you have further conditions, add the ~iflag for case-insensitive, or can filter combined lists.

虽然glob有类似的额外语法。如果您有更多条件,添加~i不区分大小写的标志,或者可以过滤组合列表,这通常是有意义的。

回答by Linus Kleen

PHP's glob()function let's you specify a pattern to search for.

PHP 的glob()函数让您指定要搜索的模式。

回答by Baba

You can try using GlobIterator

您可以尝试使用 GlobIterator

$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array)

回答by Database_Query

try this

尝试这个

//path to directory to scan
$directory = "../file/";

//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");

//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array

}

回答by Christopher Tarquini

glob($pattern, $flags)

glob($pattern, $flags)

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

回答by firecracker

haven't tested the regex but something like this:

还没有测试正则表达式,但类似这样:

if ($handle = opendir('/file/path')) {

    while (false !== ($entry = readdir($handle))) {
        if (preg_match('/\.txt$/', $entry)) {
            echo "$entry\n";
        }
    }

    closedir($handle);
}