应该在文件名中添加 +1 的 php 会将文件移到后面


Php that should add +1 to a file name instead moves file to the back

所以我有点问题。我正在尝试创建一些东西,一旦运行就会检查它试图另存为存在的文件是否存在,如果存在,它将现有文件重命名为编号 +1,它应该做的是如果该文件存在然后重命名该文件。

所以基本上
1(一) 2(二) 3(C)
将文件 X 另存为 1
1(X) 2(A) 3(B) 4(C)

但目前它不是将第一个文件重命名为最后一个数字,我不确定如何解决它。

它在做什么
1(一) 2(二) 3(C)
将文件 X 另存为 1
1(X) 2(B) 3(C) 4(A)

<?php
ob_start(); ?>
<html>
All HTML here
</html>
<?php 
$path = "cache/home-".$imputnum.".html";
?>

<?php
if (file_exists($path))     { 
        $i=$imputnum; 
        $new_path=$path;
        while (file_exists($new_path)) 
        { 
            $extension = "html"; 
            $filename = "home"; 
            $directory = "cache";
            $new_path = $directory . '/' . $filename . '-' . $i . '.' . $extension; 

            $i++;  
        } 
        if(!rename($path, $new_path)){
            echo 'error renaming file';
        }
    }
?>
<?php
$fp = fopen("cache/home-".$imputnum.".html", 'w');
fwrite($fp, ob_get_contents());
ob_end_flush();
?>

如果已经有 3 个文件,则需要重命名所有 3 个文件。例如

x-3.ext -> x-4.ext
x-2.ext -> x-3.ext
x-1.ext -> x-2.ext

(从最后到第一个)。因此,rename必须位于循环内。

下面是一个示例:

function save_file( $name, $ext, $content ) {
        $f = "$name.$ext";
        $i = 0;
        while ( file_exists( $f ) )
                $f = "$name-".++$i.".$ext";
        while ( $i > 0 )
                rename( $name.(--$i==0?"":"-$i").".$ext", "$name-".($i+1).".$ext" );
        file_put_contents( "$name.$ext", $content );
}
save_file( "home", "html", "A" );
save_file( "home", "html", "AB" );
save_file( "home", "html", "ABC" );
save_file( "home", "html", "ABCD" );

运行后,我们有:

home.html:   "ABCD"
home-1.html: "ABC"
home-2.html: "AB"
home-3.html: "A"

这是我如何做到的片段

// Get a unique filename
$filename = "$IMAGES_DIR/UploadedImg.$ext";
while(file_exists($filename)){
    $chunks = explode(".", $filename);
    $extention = array_pop($chunks);
    $basename = implode(".", $chunks);
    $num = isset($num) ? ($num+1) : 0;
    $filename = "$basename$num.$extention";
    if(file_exists($filename)) $filename = "$basename.$extention";
}

您正在尝试做的事情听起来像是array_unshift的工作,它预示着数组。见 http://php.net/manual/en/function.array-unshift.php

不带数字的基本文件名插入数组后,我将遍历数组并附加/预置索引,如下所示:

$filenames = $exising_filenames;
array_unshift($filenames, $new_filename);
foreach($filenames as $index => &$filename {
    // Do some operation to remove the numbers from filename here.
    // Now add back the number using the array's index.
    $filename = ($index+1).$filename;
    // You may rename the existing files using the filenames.
}
// Insert the new file with filename using $filenames[0]