从 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
Best way to get files from a dir filtered by certain extension in php
提问by CodeCrack
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
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 glob
has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i
flag for case-insensitive, or can filter combined lists.
虽然glob
有类似的额外语法。如果您有更多条件,添加~i
不区分大小写的标志,或者可以过滤组合列表,这通常是有意义的。
回答by Linus Kleen
回答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
<?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);
}