[英]PHP numerically rename all files in directory
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. 我有一个脚本来上传文件并用数字命名(例如1-15),当我删除文件(例如5)时,我希望将文件重命名为1-14。 This works okay if I delete a file 9 and under, if I delete anything over 10 it erases multiple files. 如果我删除文件9及以下,这行得通,如果删除10以上的文件,它将删除多个文件。 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! 谢谢!
This is because you are overwriting files while you are renaming. 这是因为重命名时将覆盖文件。
Imagine the following file list after you deleted file 11: 想象一下删除文件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. 一种解决方案:在重命名之前使用natsort($files)
对数组进行排序。
working example from php.net 来自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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.