Skip to content

Instantly share code, notes, and snippets.

@lvidal1
Created December 20, 2016 18:08
Show Gist options
  • Save lvidal1/e2ebe5c7bbe048995d9bf68a176b044f to your computer and use it in GitHub Desktop.
Save lvidal1/e2ebe5c7bbe048995d9bf68a176b044f to your computer and use it in GitHub Desktop.
Make filename friendly (slug it) recursively by giving a path directory.
<?php
// Usage:
// 1. Open console
// 2. Go to desired folder and run the script by:
// $ php friendly-filename.php
// Optional: You can pass the desired folder by argument:
// $ php friendly-filename.php /desired/folder/I/want/to/make/it/friendly
function getFriendlyFilename($filename,$extension) {
setlocale(LC_CTYPE, 'en_US.UTF8');
$filename = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $filename);
$filename = preg_replace('~[^\-\pL\pN\s]+~u', '-', $filename);
$filename = str_replace(' ', '-', $filename);
$filename = trim($filename, "-");
$filename = strtolower($filename);
return $filename.".".$extension;
}
// Get absolute path where script is runned
$path = dirname(__FILE__);
// If you want, you can pass by argument a new path
if(isset($argv[1])){
if(is_dir($argv[1])){
$path = $argv[1];
}
}
// Build iterator
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($rii as $file) {
// Check if dir, to continue
if ($file->isDir()){
print_r("\t".$file->getPath()."\n\t---------------------- \n");
continue;
}
// Get filename
$filename = $file->getBasename('.'.$file->getExtension());
// Get extension
$extension = $file->getExtension();
// Build new name
$newName = getFriendlyFilename($filename,$extension);
// Set Old path
$oldPath = $file->getPathname();
// Set new path
$newPath = $file->getPath()."/".$newName;
// Rename old info to new info
rename($oldPath,$newPath);
// Output processed file
print_r("\tOld: ".$oldPath." \n\tNew: ".$newPath."\n\n");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment