如何使用PHP递归更改所有文件扩展名

huangapple go评论57阅读模式
英文:

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 &#39;&lt;ul&gt;&#39;;
      foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo-&gt;isDot()) {
          echo &#39;&lt;li&gt;&#39; . $fileInfo-&gt;getFilename();
          if (substr($fileInfo-&gt;getFilename(),-8) == &quot;.pdf.pdf&quot;){
             rename($fileInfo-&gt;getPathname(),substr($fileInfo-&gt;getPathname(),0,-4));
          }
          if ($fileInfo-&gt;isDir()) {
            listFolderFiles($fileInfo-&gt;getPathname());
          }
          echo &#39;&lt;/li&gt;&#39;;
        }
      }
      echo &#39;&lt;/ul&gt;&#39;;
    }
    listFolderFiles(&#39;job&#39;);

I hope this helps someone else sometime!

</details>



huangapple
  • 本文由 发表于 2023年3月7日 07:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定