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,
eg 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!
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++;
}
This should help you; however, I am going to assume permissions are correct on the server and you are able to rename from a script:
// 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.