PHP仅通过其扩展名

时间:2017-06-26 13:24:58

标签: php

我试图重命名一个文件而不知道它的'当前名称,只知道它的'扩展名(目录中只有一个带有此特定扩展名的文件)。通常,我会像这样使用星号:

rename("users/*.txt","users/testing.txt");

但是,当我知道它时,我收到一条警告,说明没有这样的文件。

1 个答案:

答案 0 :(得分:4)

使用glob()检索.txt个文件的列表(通常只有一个文件名),而不是尝试使用rename()的通配符。

在错误案例事件中,有多个文件,您有机会做一些事情来处理错误。

// List all text files...
$files = glob("users/*.txt");
$numfiles = count($files);

if ($numfiles == 1) {
  // Rename it
  rename($files[0], "users/testing.txt");
}
else if ($numfiles > 1) {
  // Something is wrong - there are too many text files
  // error handling...
}
else {
  // no text file, no action, or raise an error if it's missing...
}
相关问题