简体   繁体   中英

Renaming all files within different sub directories

I m trying to rename files to lowercase within a directory, however the problem I'm having is being able to scan the sub-directories for the files.

So in this case $app_dir is the main directory and the files I need to change exist within multiple sub-folders.

Heres my code so far:

$files = scandir($app_dir);
foreach($files as $key=>$name){
$oldName = $name;
$newName = strtolower($name);
rename("$app_dir/$oldName","$app_dir/$newName");
}

Thanks for your help.

You could do this with a recursive function.

function renameFiles($dir){
    $files = scandir($dir);
    foreach($files as $key=>$name){
        if($name == '..' || $name == '.') continue;
        if(is_dir("$dir/$name"))
            renameFiles("$dir/$name");
        else{
            $oldName = $name;
            $newName = strtolower($name);
            rename("$dir/$oldName", "$dir/$newName");
        }
    }
}

This basically loops through a directory, if something is a file it renames it, if something is a directory it runs itself on that directory.

If you are trying to lowercase all file names you can try this:

Using this filesystem:

Josh@laptop:~$ find josh
josh
josh/A
josh/B
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t

Code:

<?php
$app_dir = 'josh';
$dir = new RecursiveDirectoryIterator($app_dir, FilesystemIterator::SKIP_DOTS);
$iter = new RecursiveIteratorIterator($dir);
foreach ($iter as $file) {
    if ($file != strtolower($file)) {
        rename($file, strtolower($file));
    }
}

Results:

Josh@laptop:~$ find josh
josh
josh/a
josh/b
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t

This code does not take into account uppercase letters in directories but that exercise is up to you.

Try like that

public function renameFiles($dir)
{
    $files = scandir($dir);
    foreach ($files as $key => $name) {
        if (is_dir("$dir/$name")) {
            if ($name == '.' || $name == '..') {
                continue;
            }
            $this->renameFiles("$dir/$name");
        } else {
            $oldName = $name;
            $newName = strtoupper($name);
            rename("$dir/$oldName", "$dir/$newName");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM