【问题标题】:rename all files and folders in a path重命名路径中的所有文件和文件夹
【发布时间】:2017-11-14 10:36:55
【问题描述】:

我想递归查找特殊路径中的所有文件和文件夹,我用这段代码来做

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

我想用空格替换名称,下划线 所以我用这段代码来做

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

但是当我重命名父文件夹时出现问题,因此系统无法重命名子文件夹和文件,因为路径更改或丢失 那么我该如何解决我的问题呢?

【问题讨论】:

  • 从重命名文件名开始,然后才重命名它们的父目录。从底部开始... :)

标签: php


【解决方案1】:

这是递归重命名文件和文件夹的工作代码,

<?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

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多