【问题标题】:Find the most recent file starting with [duplicate]查找以 [重复] 开头的最新文件
【发布时间】:2013-08-05 09:18:03
【问题描述】:

我希望通过共轭函数来查找以以下开头的最新文件:

$path = "/home/www/images/xml_cache"; 
$nom="images_album_6*.xml";

foreach (glob($path.'/'.$nom.'') as $filename) { }

  $latest_ctime = 0;
  $latest_filename = '';  
  $d = dir($path);
  while (false !== ($entry = $d->read( )))  {
    $filepath = "{$path}/{$entry}";
    // could do also other checks than just checking whether the entry is a file
    if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
      $latest_ctime = filectime($filepath);
      $latest_filename = $entry;
    }
  }
}

但是怎么做呢?

提前谢谢你

【问题讨论】:

标签: php glob


【解决方案1】:

假设你有PHP5,你可以使用RecursiveIterator类和getMTime函数:

$path = "/home/www/images/xml_cache"; 
$pattern = "/^images_album_6\S+.xml/i";
$latest_time = 0;
$latest_filename = '';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $file) {
    if ($file->isFile() && preg_match($pattern,$file->getFilename())) {
        if ($file->getMTime() > $latest_time) {
            $latest_time = $file->getMTime();
            $latest_filename = $file->getPathname();
        }
    }
}
print("Latest file: ".$latest_filename.PHP_EOL);

这将递归检查您指定的路径并打印与您的文件名模式匹配的最新文件的完整路径。

【讨论】:

  • 您好,它有效!我不知道如何感谢你,但我想请你喝一杯;-) 非常感谢你
  • @PhilippeLG,您可能想使用Stackoverflow Tour,因为它将指导您如何最好地使用本网站来解决您将来可能遇到的问题。
猜你喜欢
  • 2015-11-10
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多