PHP:如何重命名文件夹

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP:如何重命名文件夹脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想问你一件小事.
我在主文件夹中有一些其他文件夹.
这个子文件夹命名为:

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

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

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

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

脚本宝典总结

以上是脚本宝典为你收集整理的PHP:如何重命名文件夹全部内容,希望文章能够帮你解决PHP:如何重命名文件夹所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。