获取编号最高的文件并创建下一个文件

时间:2013-01-09 12:12:00

标签: php

我有一个包含名为standard_xx.jpg(xx是数字)

的文件的文件夹

我想找到最高的数字,以便我可以准备好重命名下一个上传文件的文件名。

EG。如果最高的数字是standard_12.jpg $ newfilename = standard_13.jpg

我已经创建了一个方法来实现它只是爆炸文件名,但它不是很优雅

$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
$maxfile = $files[count($files)-1];
$explode = explode('_',$maxfile);
$filename = $explode[1];
$explode2 = explode('.',$filename);
$number = $explode2[0];
$newnumber = $number + 1;
$standard = 'test-xrays-del/standard_'.$newnumber.'.JPG';
echo $newfile;

有更高效或更优雅的方式吗?

4 个答案:

答案 0 :(得分:2)

您可以使用sscanfDocs

$success = sscanf($maxfile, 'standard_%d.JPG', $number);

它不仅可以让您选择号码(只有号码),还可以选择是否有效($success)。

此外,您还可以查看natsortDocs以实际排序您获得的最高自然数字的数组。

使用这些的完整代码示例:

$mask   = 'standard_%s.JPG';
$prefix = 'test-xrays-del';    
$glob   = sprintf("%s%s/%s", $uploaddir, $prefix, sprintf($mask, '*'));
$files  = glob($glob);
if (!$files) {
    throw new RuntimeException('No files found or error with ' . $glob);
}

natsort($files);

$maxfile = end($files);
$success = sscanf($maxfile, sprintf($mask, '%d'), $number);
if (!$success) {
    throw new RuntimeException('Unable to obtain number from: ', $maxfile);
}

$newnumber = $number + 1;
$newfile   = sprintf("%s/%s", $prefix, sprintf($mask, $newnumber));

答案 1 :(得分:2)

我自己就是这样做的:

<?php

    $files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
    natsort($files);
    preg_match('!standard_(\d+)!', end($files), $matches);
    $newfile = 'standard_' . ($matches[1] + 1) . '.JPG';
    echo $newfile;

答案 2 :(得分:1)

尝试:

$files   = glob($uploaddir.'test-xrays-del/standard_*.JPG');
natsort($files);
$highest = array_pop($files);

然后用正则表达式获取它的数字并增加值。

答案 3 :(得分:0)

这样的事情:

function getMaxFileID($path) {
    $files = new DirectoryIterator($path);
    $filtered = new RegexIterator($files, '/^.+\.jpg$/i');
    $maxFileID = 0;

    foreach ($filtered as $fileInfo) {
        $thisFileID = (int)preg_replace('/.*?_/',$fileInfo->getFilename());
        if($thisFileID > $maxFileID) { $maxFileID = $thisFileID;}
    }
    return $maxFileID;
}