tags:

views:

57

answers:

2

I need a function which searches a dir for UP TO 5 files (only MAX 5 files in the dir). The files have the same names almost, an ID nr ending with '_1' for file 1, '_2' for file 2 etc. It simply ends with a underscore, and then the file-nr. Example:

   filename = id.'_1.jpg'; // File 1.

Here is the tricky part, read carefully: Now I need to search this dir and if there is (for example) a file1, and file3, BUT NO file2, then rename file3 to file2.

In other words, I need to find 'gaps' between the names and rename all files so they come in order, without 'gaps'.

So another example, if dir contains 3 files ending with '_1.jpg' and '_3.jpg' and '_4.jpg' I want it to rename the files so that they are '_1.jpg' and '_2.jpg' and '_3.jpg', they come in order...

As I said there is max 5 files in this folder.

Please help me out... I am not that good in writing functions in PHP... Thanks

PS: If I'm not clear, let me know and I will put in some more examples...

+1  A: 

This is not necessarily the most elegant solution, but it might get you started.

function shuffleFiles($dirPath,$basename, $extension)
{
   $MAXFILES = 5;
   $originalFilenames = array();
   for($i = 1; $i <= $MAXFILES; $i++) // one-based
   {
     $name = $dirPath . '/' . $basename . '_' . $i . '.' . $extension;
     if(file_exists($name))
     {
        $originalFilenames[] = $name;
     }
   }
   $i = 0;
   foreach($originalFilenames as $oldname)
   {
      $i++;
      $newname = $dirPath . '/' . $basename . '_' . $i . '.' . $extension;
      rename($oldname, $newname);
   }     
}
Ewan Todd
A: 

Works on any number of files per dir

function cleanUpMess($dir, $ext, $delimiter) {

  $files = glob($dir.'/*.'.$ext);
  $c = 1;

  foreach ($files as $file) {

    $secondPart = strrchr($file, $delimiter);
    $name = explode($secondPart, $file);
    $name = $name[0];

    $newFile = $name.$delimiter.$i.'.'.$ext;
    rename($file, $new);
    $c++;

  }

}
code_burgar