PHP:如何重命名文件夹

4
我希望请你帮我做一件小事。
在一个主文件夹下,我有另外几个文件夹。
这些子文件夹的名称为:

v1, v2, v3, v4...

我想知道,如果我删除其中一个文件夹,
例如v2 -> 那么我会拥有v1、v3和v4
如何将所有这些文件夹重新命名为

v1、v2、v3。

我尝试了下面的代码,但它不起作用:
$path='directory/';
$handle=opendir($path);
$i = 1;
while (($file = readdir($handle))!==false){
    if ($file!="." && $file!=".."){
        rename($path . $file, $path . 'v'.$i);
        $i++;
    }

谢谢!

使用调试器或者“穷人版”的调试方法——输出 $file 的值,来检查它是否符合你的预期。 - Halfstop
这个文件夹里还有其他目录,还是只有v*这个目录? - Hexchaimen
2个回答

2

该代码检索所有以"v"开头并跟随数字的目录。

过滤后的目录:v1、v2、v3、......
排除的目录:v_1、v2_1、v3a、t1、"."、".."、xyz

最终目录:v0、v1、v2、v3、......

如果需要从v1开始,则需要再次获取目录列表并执行一次重命名过程。希望这可以帮助您!

$path='main_folder/'; $handle=opendir($path); $i = 1; $j = 0; $foldersStartingWithV = array();  

// Folder names starts with v followed by numbers only
// We exclude folders like v5_2, t2, v6a, etc
$pattern = "/^v(\d+?)?$/";

while (($file = readdir($handle))!==false){
    preg_match($pattern, $file, $matches, PREG_OFFSET_CAPTURE);

    if(count($matches)) {
    // store filtered file names into an array
    array_push($foldersStartingWithV, $file);
    }
}

// Natural order sort the existing folder names 
natsort($foldersStartingWithV);  

// Loop the existing folder names and rename them to new serialized order
foreach($foldersStartingWithV as $key=>$val) {
// When old folder names equals new folder name, then skip renaming
    if($val != "v".$j) {
        rename($path.$val, $path."v".$j);
    }
    $j++;
}

使用natsort()真不错!! - Hexchaimen

1
这应该对你有所帮助;不过,我假设服务器的权限正确,并且你能够从脚本中重命名。
// Set up directory
$path = "test/";
// Get the sub-directories
$dirs = array_filter(glob($path.'*'), 'is_dir');
// Get a integer set for the loop
$i=0; 
// Natural sort of the directories, props to @dinesh
natsort($dirs);

foreach ($dirs as $dir)
{ 
    // Eliminate any other directories, only v[0-9]
    if(preg_match('/v.(\d+?)?$/', $dir)
    {
      // Obtain just the directory name
      $file = end(explode("/", $dir));
      // Plus one to your integer right before renaming.
      $i++;
      //Do the rename
      rename($path.$file,$path."v".$i);
    }
}

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