我希望递归地找到特殊路径中的所有文件和文件夹,并使用此代码
public static function getDirContents($dir, &$results = array()){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
$results[] = $path;
} else if($value != "." && $value != "..") {
self::getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
我希望用空格替换名称,Underscore 所以我用这个代码
$files = FileHelper::getDirContents($path_from);
if (isset($files)) {
$replacers = array(" ", " ", "-", "!", ":", ";", "#", "@", "'");
foreach ($files as $file) {
$newName = str_replace($replacers, "_", $file);
if ($newName != $file) {
Logger::setLog('renaming', "Renaming: $file to $newName");
rename($file, $newName);
}
}
}
但是当我重命名父文件夹时出现问题,因此系统无法重命名子文件夹和文件,因为路径已更改或错过 那我怎么能解决我的问题?
答案 0 :(得分:0)
以下是递归重命名文件和文件夹的工作代码,
<?php
renameFiles('C:\assets\images\\','doctor'); // target path is C:\assets\images\doctor
function renameFiles($base,$path){
$replacers = array(" ", " ", "-", "!", ":", ";", "#", "@", "'");
foreach (new DirectoryIterator($base.$path) as $object) {
if($object->isDot()) continue;
if(is_dir($base.$path.'\\'.$object->getFilename())){
renameFiles($base,$path.'\\'.$object->getFilename());
}
$oldName = $object->getFilename();
$newName = str_replace($replacers, "_", $oldName);
$oldFullName = $object->getPath() . DIRECTORY_SEPARATOR . $oldName;
$newFullName = $object->getPath() . DIRECTORY_SEPARATOR . $newName;
rename($oldFullName, $newFullName);
echo "old : $oldName , new: $newName <br/>\n";
//echo $object->getFilename() . "<br>\n";
}
}
?>
我上面的示例目标路径是C:\assets\images\doctor