PHP:如何重命名文件夹

我想问你一件小事.
我在主文件夹中有一些其他文件夹.
这个子文件夹命名为:

v1,v2,v3,v4…

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

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

如何将所有这些文件重命名

v1,v3.

我试过这段代码,但它不起作用:

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

谢谢!

解决方法

代码检索名称以“v”开头的所有目录,后跟数字.

目录已过滤:v1,…..
排除目录:v_1,v2_1,v3a,t1,.,..,xyz

最终目录:v0,v1,…..

如果最终目录需要从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++;
}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...