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


Get highest numbered file and create next one

我有一个文件夹,包含名为standard_xx.jpg (xx是一个数字)的文件

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

。如果最大的数字是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;

是否有更有效或更优雅的方法来做到这一点?

我自己会这样做:

<?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;

您可以使用sscanf Docs:

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

它不仅允许您挑选数字(并且只有数字),而且还允许您选择是否工作($success)。

此外,您还可以查看natsort Docs来实际排序您返回的最高自然数的数组。

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

$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));

Try with:

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

像这样:

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;
}