Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

File renaming / reordering



12:29 am on Aug 20, 2012 (gmt 0)

10+ Year Member

So, say a directory has some image files named like this:


Can you create a simple script to rename any file
above name-1.jpg in ascending order, so the result is:


Just looking for ideas, hoping someone has done this before. Thanks in advance for any info.


12:58 am on Aug 20, 2012 (gmt 0)

WebmasterWorld Administrator incredibill is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

I haven't done it exactly like that but it's easy.

I would first rename the original files so they don't confuse the code to oldname*.jpg to avoid an infinite loop or something. Then write a simple loop that reads the directory, counts each file, and renames them or, instead of renaming them first, just load the list into an array.

Off the top of my head something like this would work, I didn't run it, didn't test it, just showing how it could be done.

$files = scandir( 'oldname*.jpg' );
while ($oldfile = current($files)) {
$newfile='name-' . $num . '.jpg';
rename( $oldfile, $newfile);

If the files need to maintain the same order you would load them into an array first and sort it, then iterate the file names from the array instead of current(), which also avoids renaming them in advance as mentioned above.

Hope that gets you started!


1:33 pm on Aug 20, 2012 (gmt 0)

10+ Year Member

Thanks! I'll pursue that. I figured I had to create an array of file names and use rename() but wasn't exactly sure how.


8:13 pm on Aug 20, 2012 (gmt 0)

10+ Year Member

I came up with this, using foreach() and glob():

$prefix="name"; //will be script generated to ensure unique set names

foreach (glob("some_directory/".$prefix."-*.jpg") as $filename) {
rename( $filename, "some_directory/".$prefix."-".$num.".jpg");

Featured Threads

Hot Threads This Week

Hot Threads This Month