Return to Snippet

Revision: 32942
at October 5, 2010 02:37 by sweatyman


Initial Code
function massrename($dir) {

    $files = glob($dir . '/*');
    foreach ($files as $file) {
    
        $pathinfo = pathinfo($file);
        $newname = strtolower($pathinfo['basename']);
        // replace spaces with hyphens and remove funny characters
        $newname = str_replace(' ', '-', $newname);
        $newname = preg_replace('/[^\d\w\._-]/', '', $newname);
        // make sure there's something left
        $newname = $newname ? $newname : 'file';
        // prevent renaming over an existing file
        while ($newname !== $pathinfo['basename'] && file_exists($dir . '/' . $newname)) {
            $newname = '_' . $newname;
        }
        rename($file, $dir . '/' . $newname) || die('o no there was an error');
        is_dir($dir . '/' . $newname) && massrename($dir . '/' . $newname);
    } 
}

Initial URL

                                

Initial Description

                                

Initial Title
rename multiple files/directories to lowercase, removing spaces & funny characters

Initial Tags

                                

Initial Language
PHP