Home Account

rename files recursively php

2012-01-31 17:14 dennis iversen

Tags: php scripts-and-functions

<?php

/**
 * function will rename all dirs and files recursively
 * @param type $start_dir 
 * @param type $debug (set false if you don't want the function to echo)
 */
function rename_recursive($start_dir, $debug = true) {
    $str = "";
    $files = array();
    if (is_dir($start_dir)) {
        $fh = opendir($start_dir);
        while (($file = readdir($fh)) !== false) {
            // skip hidden files and dirs and recursing if necessary
            if (strpos($file, '.')=== 0) continue;

            $filepath = $start_dir . '/' . $file;
            if ( is_dir($filepath) ) {
                $newname = sanitize_file_name($filepath);
                $str.= "From $filepath\nTo $newname\n";
                rename($filepath, $newname);
                rename_recursive($newname);
            } else {
                $newname = sanitize_file_name($filepath);
                $str.= "From $filepath\nTo $newname\n";
                rename($filepath, $newname);
            }
        }
        closedir($fh);
    }
    if ($debug) {
        echo $str;
    }
}

/**
 * function for modifing to a safe dir og filename
 * Taken from from wordpress. 
 * @param string $filename
 * @return string $newname 
 */
function sanitize_file_name( $filename ) {
    $filename_raw = $filename;
    $special_chars = array("?", "[", "]", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
    $filename = str_replace($special_chars, '', $filename);
    $filename = preg_replace('/[\s-]+/', '-', $filename);
    $filename = trim($filename, '.-_');
    return $filename;
}

$start_dir = '/home/dennis/skansen';
$files = rename_recursive($start_dir);

This page has been requested 8634 times