英文:
How to recursively change all file extension with php
问题
我在想是否有一种方法可以递归地从一个目录及其子目录和子子目录中更改文件扩展名从php到其他扩展名?
我继承了一个项目,它曾经在一个Windows服务器上,不知何故,所有的PDF文件都以.pdf.pdf的扩展名上传。例如,文件名.pdf.pdf。
我正在将这个项目迁移到一个LAMP服务器。
如果可能的话,我想将这些文件重命名为文件名.pdf - 它们位于目录和子目录以及子子目录中。
这是否有可能做到?我完全不知所措。
英文:
I am wondering if there is a way to recursively change file extensions from php within a directory and its subdirectories and subsubdirectories?
I have inherited a project that was on a windows server and somehow all pdf files have been uploaded with the extension .pdf.pdf  Example filename.pdf.pdf
I am migrating the project to a LAMP server.
I would like to rename the files if possible to filename.pdf - They sit within directories and sub and subsubdirectories.
Is this something that is do-able at all?
I am completely at a loss.
答案1
得分: 1
虽然有点凌乱,但我成功解决了我的问题,使用以下代码:
function listFolderFiles($dir){
  echo '<ul>';
  foreach (new DirectoryIterator($dir) as $fileInfo) {
    if (!$fileInfo->isDot()) {
      echo '<li>' . $fileInfo->getFilename();
      if (substr($fileInfo->getFilename(), -8) == ".pdf.pdf"){
         rename($fileInfo->getPathname(), substr($fileInfo->getPathname(), 0, -4));
      }
      if ($fileInfo->isDir()) {
        listFolderFiles($fileInfo->getPathname());
      }
      echo '</li>';
    }
  }
  echo '</ul>';
}
listFolderFiles('job');
希望这对其他人有所帮助!
<details>
<summary>英文:</summary>
Although somewhat messy, I was able to resolve my issue with the following code:
    function listFolderFiles($dir){
      echo '<ul>';
      foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
          echo '<li>' . $fileInfo->getFilename();
          if (substr($fileInfo->getFilename(),-8) == ".pdf.pdf"){
             rename($fileInfo->getPathname(),substr($fileInfo->getPathname(),0,-4));
          }
          if ($fileInfo->isDir()) {
            listFolderFiles($fileInfo->getPathname());
          }
          echo '</li>';
        }
      }
      echo '</ul>';
    }
    listFolderFiles('job');
I hope this helps someone else sometime!
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论