此代碼檢索所有開頭「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++;
}
檢查$文件是你認爲它應該與調試器,或窮人的調試echo $文件; – Halfstop
該文件夾中的任何其他目錄,或只是v *? – Hexchaimen