PHP以数字方式重命名目录中的所有文件

发布于 2024-10-02 23:58:39 字数 380 浏览 0 评论 0原文

我有一个脚本来上传文件并以数字命名(例如 1-15),当我删除文件(例如数字 5)时,我希望将文件重命名为 1-14。如果我删除 9 及以下的文件,这可以正常工作,如果我删除超过 10 的文件,它会删除多个文件。据我所知,问题不在于删除,而在于重命名

这是我遇到问题的脚本片段:

unlink($path.$img);

$files = natsort(glob("$path/*.jpg"));

$num = 1;

foreach($files as $file) {
  $new = 'photo' . $num . '.jpg'; 
  rename($file, dirname($file).'/'.$new);
  $num++;
}

谢谢!

I have a script to upload files and name them numerically (say 1-15) and when I delete a file (say number 5) I want the files to be renamed 1-14. This works okay if I delete a file 9 and under, if I delete anything over 10 it erases multiple files. As far as I can tell the problem isn't with the deletion but the renaming

Here's the piece of script I'm having trouble with:

unlink($path.$img);

$files = natsort(glob("$path/*.jpg"));

$num = 1;

foreach($files as $file) {
  $new = 'photo' . $num . '.jpg'; 
  rename($file, dirname($file).'/'.$new);
  $num++;
}

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

献世佛 2024-10-09 23:58:39

这是因为您在重命名时覆盖了文件。

想象一下删除文件 11 后的以下文件列表:

1
10
12
2
3
4
5
...

如果您现在开始重命名,则会发生以下情况:

1 -> 1
10 -> 2
12 -> 3
2 -> already overwritten by 10!

一种解决方案:在重命名之前使用 natsort($files) 对数组进行排序。

This is because you are overwriting files while you are renaming.

Imagine the following file list after you deleted file 11:

1
10
12
2
3
4
5
...

If you now start renaming, the following happens:

1 -> 1
10 -> 2
12 -> 3
2 -> already overwritten by 10!

One solution: Sort your array using natsort($files) before renaming.

攒一口袋星星 2024-10-09 23:58:39

来自 php.net 的工作示例

 <?php 
$path = "E:\\SERVER\\sudhir\\songs"; 
$dh = opendir($path); 
$i=1; 
while (($file = readdir($dh)) !== false) { 
    if($file != "." && $file != "..") { 
        echo "<br/>".substr($path."\\".$file, 0,-3)."_mysongs_mp3"; 
        rename($path."\\".$file, substr($path."\\".$file, 0,-3)."_mysongs_mp3"); 
        $i++; 
    } 
} 
closedir($dh); 
?>

working example from php.net

 <?php 
$path = "E:\\SERVER\\sudhir\\songs"; 
$dh = opendir($path); 
$i=1; 
while (($file = readdir($dh)) !== false) { 
    if($file != "." && $file != "..") { 
        echo "<br/>".substr($path."\\".$file, 0,-3)."_mysongs_mp3"; 
        rename($path."\\".$file, substr($path."\\".$file, 0,-3)."_mysongs_mp3"); 
        $i++; 
    } 
} 
closedir($dh); 
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文