Skip to content

Instantly share code, notes, and snippets.

@timmyRS
Last active April 26, 2017 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timmyRS/11b0680d07678d7d6fd9095bf3c162fc to your computer and use it in GitHub Desktop.
Save timmyRS/11b0680d07678d7d6fd9095bf3c162fc to your computer and use it in GitHub Desktop.
Rename files in a directory just the way you'd like to.
<?php
// Your configuration starts here.
// Testing. 'true' = Don't actually edit files and only output the name changes.
$testing = false;
// Folders. 'true' = Rename folders and files.
$folders = true;
// Recursive. 'true' = Also rename files in sub-directories.
$recursive = true;
// Your configuration ends here.
function renameRule($name, $prefix)
{
// Your custom rename rule starts here.
// Change $name however you like.
// Prefix debug outputs with $prefix.
$extension = array_reverse(explode(".", $name))[0];
$name = substr($name, 0, -(strlen($extension) + 1));
$name = str_replace([".", "_"], " ", $name);
$name .= ".".$extension;
// Your custom rename rule ends here.
return $name;
}
function renameDir($dir, $prefix)
{
global $argv, $testing, $folders, $recursive;
foreach(scandir($dir) as $file)
{
$path = $dir."/".$file;
if($path == "./".$argv[0])
{
continue;
}
if($folders || !is_dir($path))
{
$newname = renameRule($file, $prefix);
$newpath = $dir."/".$newname;
if($file != $newname)
{
if(!file_exists($dir."/".$newname))
{
if($testing)
{
echo $prefix."'{$file}' would now be '{$newname}'\n";
} else
{
echo $prefix."'{$file}' is now '{$newname}'\n";
rename($path, $newpath);
}
} else
{
echo $prefix."CANT RENAME '{$file}' because '{$newname}' already exists!\n";
}
}
}
if($recursive && !in_array($file, [".", ".."]))
{
if(file_exists($path) && is_dir($path))
{
echo $prefix.$path."\n";
renameDir($path, $prefix." ");
}
else if(file_exists($newpath) && is_dir($newpath))
{
echo $prefix.$newpath."\n";
renameDir($newpath, $prefix." ");
}
}
}
}
renameDir(".", "");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment