Renaming filenames

Hi,

I have a series of files that are currently ordered by a number:

(ignore the 1000 number) eg.

filename-1000-1_t.jpg
filename-1000-1.jpg
filename-1000-12_t.jpg
filename-1000-12.jpg
filename-1000-13_t.jpg
filename-1000-13.jpg
filename-1000-2_t.jpg
filename-1000-2.jpg

I need to rename 1-5 according to that ordering:

filename-1000-1_t.jpg
filename-1000-1.jpg
filename-1000-2_t.jpg
filename-1000-2.jpg
filename-1000-3_t.jpg
filename-1000-3.jpg
filename-1000-4_t.jpg
filename-1000-4.jpg

Of course, I have to be careful of not overwriting the -2_t.jpg and -2.jpg files in the above scenario. What is the best way to achieve this?

Try this BUT first make sure that you save the $old files.


$old=array 
(
'filename-1000-1_t.jpg',
'filename-1000-1.jpg',
'filename-1000-12_t.jpg',
'filename-1000-12.jpg',
'filename-1000-13_t.jpg',
'filename-1000-13.jpg',
'filename-1000-2_t.jpg',
'filename-1000-2.jpg',
);
// Created OLD files for testing
foreach($old as $id => $x)
{
   # echo '<br />'.file_put_contents($x, $x);
}

$new=array 
(
'filename-1000-1_t.jpg',
'filename-1000-1.jpg',
'filename-1000-2_t.jpg',
'filename-1000-2.jpg',
'filename-1000-3_t.jpg',
'filename-1000-3.jpg',
'filename-1000-4_t.jpg',
'filename-1000-4.jpg',
);


$tmp =array();
echo '<pre>';
    #print_r($old);
    #print_r($new);

// rename $old files with '_TMP_' prefix
    $tmp = array();
    for($i2=0; $i2 < count($old); $i2++)
    {
      $tmp[] = '_TMP_' .$old[$i2];
      #echo '<br />rename(' .$old[$i2] .',&nbsp;&nbsp;  _TMP_' .$old[$i2] .');';
      rename($old[$i2], '_TMP_' .$old[$i2] );
    }


// rename $tmp files to $new file names
    for($i2=0; $i2 < count($new); $i2++)
    {
      #echo '<br />rename(' .$tmp[$i2] .',&nbsp;&nbsp;' .$new[$i2] .');';
      rename($tmp[$i2], $new[$i2] );
    }


echo '</pre>';



Are you sure you don’t want to have natsort() in there somewhere?
*has an example very much like what you describe.

How about a first loop to temporarily rename all files with something like :
_filename-1000-1_t.jpg
_filename-1000-1.jpg
_filename-1000-12_t.jpg
etc…

Then, get the list of the files in the folder in alphabetical order and rename them according to what you need.

Something like:

// First, rename all the files temporarily with an underscore
$files = array();
$dir = opendir('.'); 
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                rename($file, '_' . $file);
        }   
}

// Get all the files in an array
$files = array();
$dir = opendir('.'); 
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                $files[] = $file; // put in array.
        }   
}

// Order the files alphabetically
natsort($files);

// Rename the files
$fileIndex = 0;
foreach($files as $file) {
      $fileIndex++;
     // Remove the temporary "_" + rename the number according to $fileindex
}