PHP中按顺序重命名所有文件

3
我有以下文件:
1.jpg
2.jpg
3.jpg
4.jpg

当我删除2.jpg时,我希望3.jpg变成2.jpg4.jpg变成3.jpg
我尝试使用rename函数的for循环,但似乎不起作用。
for($a = $i;$a < $filecount;$a ++)
{
    rename('photo/'.($a+1).'.jpg', 'photo/'.   ($a).'.jpg');
}

$i 是我刚刚删除的照片的编号。


你的意思是你先删除它们,然后再尝试重命名它们吗?你不能先删除照片,你只能将其重命名吗?你要删除什么? - b01
不,我正在删除一个文件,然后我想要重命名剩下的文件,否则就会出现间隙。如果我有1、2、3、4这样的文件,我删除了2,那么剩下的应该是1、3、4,而不是1、2、3。 - Henk Jansen
@1ntello 你为什么想要这样做?说实话,我想不出任何理由。 - Berry Langerak
我有一些需要上传的图片,我将它们命名为1、2、3、4、5、6、7进行上传。这些照片都有相应的描述,这些描述被添加到一个文本文件中。现在,文本文件中的第一条规则匹配图片编号1,以此类推。因此,如果我删除了2号图片,其余的图片名称就必须更改,否则描述就会出错。 - Henk Jansen
4个回答

5

按名称列出所有文件:

$files = glob('../photos/*');

对于每个文件,如果需要的话,请将其重命名:

foreach($files as $i => $name) {
    $newname = sprintf('../photos/%d.jpg', $i+1);
    if ($newname != $name) {
        rename($name, $newname);
    }
}

*是文件夹的路径?你能添加一些描述吗? - Henk Jansen
你们两个应该看一下这个:http://php.net/manual/en/function.glob.php - Marc Towler
  • 表示当前文件夹中的所有文件
- Arnaud Le Blanc
是的,但如果我的图片在另一个文件夹中怎么办?我有一个index.php文件,基本上处理删除等操作,但我的图片在../photo/文件夹中。 - Henk Jansen
现在我有0.jpg、1.jpg和2.jpg,当我删除1时,它会将0重命名为1,但2必须变成1。 - Henk Jansen
这是因为在你的问题中,文件从1开始。只需在代码中删除+1即可。 - Arnaud Le Blanc

0
为什么不直接删除您不再需要的文件,然后将剩余的所有文件重命名为以1开始的顺序?例如:
<?php
  $fileToRemove= '3.jpg';
  unlink($fileToRemove);

  $cnt = 0;
  if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            rename($file, ++$cnt+".jpg");
        }
    }
    closedir($handle);
  }
?>

这样,您始终可以确保序列正确。如果您有很多文件,当然可以从要删除的文件的编号开始重命名。


0
我会这样做:
echo "<pre>";
$files = array('file1.jpg', 'file5.jpg', 'file7.jpg', 'file9.jpg');

function removeElement($array, $id){
    $clone = $array; // we clone the array for naming usage
    $return = array(); // the array returned for testing purposes
    $j = 0;
    foreach($array as $num => $file){ // loop in the elements
        if($file != $id){ // check if the current file is not the element we want to remove 
            if($num == $j){ // if current element and '$j' are the same we do not need to rename that file
                $return[] = "// @rename('".$file."', '".$file."'); -- do not rename";
            } else { // if previously we have removed the file '$id' then '$j' should be -1 and we rename the file with the next one stored in '$clone' array
                $return[] = "@rename('".$file."', '".$clone[($num-1)]."'); // rename";
            }
        } else { // this is for the file we need to remove, we also -1 current '$j'
            $j--;
        }
        $j++;
    }
    return $return;
}

print_r(removeElement($files, 'file5.jpg'));

看起来很基础,但它很实用且易于阅读。


-1
$filecount = 5;
$i = 2;

unlink('photo/'. $i . '.jpg');
for($i; $i < $filecount; $i++) {
    rename('photo/'. ($i+1) .'.jpg', 'photo/'. $i . '.jpg');
}
die;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接