zoukankan      html  css  js  c++  java
  • 遍历目录,重命名目录下的文件

    下了个教程,但是没有字幕,找到外挂字幕,但是由于名字不一样,但是又有规律(0101 **** 替换成 01 01. ***),不想手动重命名,就写了个函数来批量重命名。这里写成class纯粹是多此一举,懒得改了,下面上代码,没注释,因为简单

     <?php 

    class RenameSRT {
        public function traverse($dir) {
            if (is_dir($dir)) {
                $handle = dir($dir);
                if ($handle) {
                    while (FALSE !== ($file = $handle->read())) {
                if ($file != '.' && $file != '..') {
                    $this->traverse($dir.'\\'.$file);
                }
              }
                } else {
                    echo '打开目录失败<br />';
                }
                $handle->close();
            }//echo $dir.'************';
           if (is_file($dir)) {
               $fileName = $this->getFileName($dir);
               $filePath = $this->getFilePath($dir);
               $fileType = substr($fileName, strrpos($fileName, '.')+1);
               //echo $fileType.'<br />';
               if ($fileType == 'srt') {
                 $fileReadName =  $this->getRename($fileName);
               }
           //    echo '**********'.$filePath.'\\'.$fileReadName.'************';
               if (rename($dir, ($filePath.'\\'.$fileReadName))) {
                   echo '重命名成功'.'<br />';
               }else {
                   echo '重命名失败'.'<br />';
               }
           }else {
               //echo "$dir.<br />";
           }
        }
        
        private function getFileName($filePath) {
            return basename($filePath);
        }
        
        private function getFilePath($filePath) {
            return dirname($filePath);
        }
        
        private function getRename($fileName) {
            //echo $fileName.'<br />';
            $tem = substr($fileName, 0, 4);
            //echo $tem.'<br/>';
            $replace = $tem[0].$tem[1].' '.$tem[2].$tem[3].'.';
            $tem = substr_replace($tem, $replace, 0);
            //echo $replace.'<br />';
            //echo $tem.'<br/>';
            $fileName = substr_replace($fileName, $replace , 0, 4);
            //echo $fileName.'<br />';
            return $fileName;
        }
        
        
    }

    $renamesrt = new RenameSRT();
    $renamesrt->traverse('C:\meterial\PHP');

    这里最重要的是要文件名要有规律,然后$tem按照规律的到字符串,剩下的就是substr_replace,然后rename();

  • 相关阅读:
    Cognos无法解密来着内容库的用户名和密码凭证
    JavaScript 中的对象引用
    npm install出现的错误
    箭头函数中this的用法
    [译]ArcGIS Server Map Service Cache的组织结构
    [C#] 如何选择抽象基类与接口
    数据库设计规范
    在DataTable中查询应该注意的问题
    坦克大战总结
    仓库管理系统总结(1)
  • 原文地址:https://www.cnblogs.com/hui314/p/php_file_rename.html
Copyright © 2011-2022 走看看