Advertisement
bpoole

Cleanup image file names in a directory

Feb 3rd, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.67 KB | None | 0 0
  1. <?php
  2.     //traverse a directory of images and clean up the filenames
  3.     $image_dir = '/path/to/dir/';
  4.  
  5.     if($handle = opendir($image_dir)){
  6.         while(false !== ($file_name = readdir($handle))){
  7.             if($file_name == '.' || $file_name == '..'){ continue; }
  8.             preg_match('/(.*)(\.\w+)$/', $file_name, $matches);
  9.             $image_name = $matches[1];
  10.             $image_extension = $matches[2];
  11.  
  12.             $new_name = preg_replace('/\-{2,}/', '-', preg_replace('/\W/', '-', strtolower($image_name)));
  13.  
  14.             rename("{$image_dir}{$file_name}", "{$image_dir}{$new_name}{$image_extension}");
  15.         }
  16.  
  17.         closedir($handle);
  18.     }
  19.  
  20. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement