Search code examples
phpfilebatch-rename

PHP: How to rename folders


I'd like to ask you for a one small thing.
I have a few another folders in a main folder. This sub-folders are named:

v1, v2, v3, v4...

I would like to know, when I delete one of these folders,

e.g. v2 -> so I have v1, v3, v4

how to rename all of this folders back to

v1, v2, v3.

I tried this code, but it doesn't work:

$path='directory/';
$handle=opendir($path);
$i = 1;
while (($file = readdir($handle))!==false){
    if ($file!="." && $file!=".."){
        rename($path . $file, $path . 'v'.$i);
        $i++;
    }

Thank you!


Solution

  • This code retrieves all the directories with names starting with "v" followed by numbers.

    Directories filtered: v1, v2, v3, .....
    Directories excluded: v_1, v2_1, v3a, t1, ., .., xyz

    Final directories: v0, v1, v2, v3, .....

    If the final directories needs to start from v1, then I would again get the directories list and perform one more renaming process. I hope this helps!

    $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++;
    }