搜索文件夹上已知扩展名的未知文件名

时间:2014-01-22 20:03:20

标签: php

如果知道文件的扩展名但不知道文件名,如何搜索文件夹。

假设我有一个包含这样文件的文件夹。

folder/1.txt
folder/2.txt
folder/3.txt

使用这个简单的方法我回显文件名只包含数字的所有文件。

  for ($i=0; $i<=3; $i++) {
  $files = 'folder/'. $i .'.txt';

  echo "$i.txt <br />";;     

并且上面的代码回复了这样的内容

 1.txt
 2.txt
 3.txt
如果文件名包含字母,

是否可以实现?甚至更好的字母和数字。

aaa.txt
asdwe.txt
1asw2.txt

这可能吗?

1 个答案:

答案 0 :(得分:0)

使用DirectoryIterator执行此操作:

<?php

const DS = DIRECTORY_SEPARATOR;

$dir = new DirectoryIterator('your' . DS . 'direcory' . DS);

foreach ($dir as $fileinfo) {

  if (!$fileinfo->isDot()) {
    // relative url of file = $fileinfo->getPathname();
    // file name  = $fileinfo->getFilename();
    echo $fileinfo->getFilename() . '<br />';
  }

}