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


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function massrename($dir) {
  2.  
  3. $files = glob($dir . '/*');
  4. foreach ($files as $file) {
  5.  
  6. $pathinfo = pathinfo($file);
  7. $newname = strtolower($pathinfo['basename']);
  8. // replace spaces with hyphens and remove funny characters
  9. $newname = str_replace(' ', '-', $newname);
  10. $newname = preg_replace('/[^\d\w\._-]/', '', $newname);
  11. // make sure there's something left
  12. $newname = $newname ? $newname : 'file';
  13. // prevent renaming over an existing file
  14. while ($newname !== $pathinfo['basename'] && file_exists($dir . '/' . $newname)) {
  15. $newname = '_' . $newname;
  16. }
  17. rename($file, $dir . '/' . $newname) || die('o no there was an error');
  18. is_dir($dir . '/' . $newname) && massrename($dir . '/' . $newname);
  19. }
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.