使用目录名重命名文件

时间:2016-11-17 16:47:35

标签: php file-rename

我有一些目录包含以下文件:

folder1/filename.jpg
folder2/filename.pdf
folder3/filename.jpg

我想重命名所有目录中的所有文件及其相应的目录名(但保留其扩展名),如:

folder1/filename.jpg to folder1/folder1.jpg
folder2/filename.pdf to folder2/folder2.pdf
folder3/filename.jpg to folder3/folder3.jpg

编辑:另外,我想将所有重命名的文件复制到另一个目录(如“allfiles”)。

我找到了a similar question in Perl language

我怎样才能用PHP实现它?

1 个答案:

答案 0 :(得分:2)

在这里你有办法做到这一点:

<?php

// Array with all subdirectories in directory
$dirArray = array_filter(glob('/path/to/directory/*'), 'is_dir');

// $dir is the path to the subdirectory
foreach ($dirArray as $dir) {

    // $dirName has the future name of files in that subdirectory
    $dirName = basename($dir);

    // Take all the elements in the subdirectory (except '.' and '..')
    $filesArray = array_diff(scandir($dir), array('.', '..'));

    $i = 0;
    foreach ($filesArray as $file) {
        // Take the file extension for the rename method
        $fileExtension = pathinfo($file, PATHINFO_EXTENSION);

        $oldName = $dir . "/" . $file;
        $newName = $dir . "/" . $dirName . "-" . $i . "." . $fileExtension;

        rename($oldName, $newName);
        $i++;
    }
}

如果您确定每个子目录中只有一个文件,则可以将此行用于$newName

$newName = $dir . "/" . $dirName . "." . $fileExtension;