Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:如何重命名文件夹_Php_File_Batch Rename - Fatal编程技术网

PHP:如何重命名文件夹

PHP:如何重命名文件夹,php,file,batch-rename,Php,File,Batch Rename,我想问你一件小事 我在主文件夹中还有几个文件夹。 此子文件夹的名称为: v1,v2,v3,v4 我想知道,当我删除其中一个文件夹时 e、 所以我有v1,v3,v4 如何将所有这些文件夹重新命名为 v1,v2,v3 我尝试了此代码,但不起作用: $path='directory/'; $handle=opendir($path); $i = 1; while (($file = readdir($handle))!==false){ if ($file!="." && $f

我想问你一件小事
我在主文件夹中还有几个文件夹。 此子文件夹的名称为:

v1,v2,v3,v4

我想知道,当我删除其中一个文件夹时

e、 所以我有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++;
    }

谢谢大家!

这应该对你有帮助;但是,我假设服务器上的权限是正确的,并且您可以从脚本重命名:

// 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);
    }
}

此代码检索名称以“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++;
}

检查$file是否与调试器或可怜人的调试echo$file的预期一致;此文件夹中的任何其他目录,或仅v*?非常适合
natsort()
!!