简体   繁体   English

如何在PHP中使用scandir获取过滤的文件名列表?

[英]How to get filtered file name list using scandir in PHP?

I would like to get all files that has '_img' and PDF type in a folder 我想在文件夹中获取所有'_img'和PDF类型的文件

Instead of using 而不是使用

$fileArray = scandir($dir);
foreach ($fileArray as $file) {
    if (preg_match("_img",$file) && pathinfo($file, PATHINFO_EXTENSION) == 'pdf'){
        $filteredArray[] = $file;
    }
}

Are there any short cut or it is the best way? 有没有捷径或者这是最好的方式? Thanks 谢谢

Use php glob() function 使用php glob()函数

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells glob()函数根据libc glob()函数使用的规则搜索匹配模式的所有路径名,这类似于常见shell使用的规则

<?php 
  $filteredArray = array();
  foreach (glob($dir."/*_img.pdf") as $filename)
     $filteredArray[] = $filename;
?>

There is also fnmatch() function which matches filename against a pattern 还有fnmatch()函数,它将文件名与模式匹配

The last solution is to use DirectoryIterator with FilterIterator 最后一个解决方案是将DirectoryIteratorFilterIterator一起使用

To me this works fine. 对我来说,这很好。 you walk into you directory and store this to an array. 你走进你的目录并将其存储到一个数组。

At this level, an optimisation is not needed. 在此级别,不需要优化。 you'll win peanuts losting time to optimize this. 你会赢得花生失去时间来优化这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM