Skip to content

Instantly share code, notes, and snippets.

@kkiernan
Last active March 1, 2016 18:23
Show Gist options
  • Save kkiernan/e500dc24086d79c29e52 to your computer and use it in GitHub Desktop.
Save kkiernan/e500dc24086d79c29e52 to your computer and use it in GitHub Desktop.
Quick script to clean up file names in a directory
<?php
/*
|---------------------------------------------------------------------
| Rename Files
|---------------------------------------------------------------------
|
| This is a simple script to renames files in the current directory.
| It converts filenames to lowercase, removes non-alphanumeric
| characters and converts spaces to dashes.
|
*/
$files = array_diff(scandir('./'), ['..', '.', 'file-name-formatter.php']);
$patterns = ['/[^A-Za-z0-9 ]/', '/ {2,}/', '/ /'];
$replacements = ['', ' ', '-'];
foreach ($files as $file) {
if (is_dir($file)) {
echo "Skipping directory $file\n";
continue;
}
$pathInfo = pathinfo($file);
$newFilename = preg_replace($patterns, $replacements, strtolower($pathInfo['filename']));
$newBasename = $newFilename . "." . $pathInfo['extension'];
rename($file, $newBasename);
echo "File renamed to: $newBasename\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment