homepage Welcome to WebmasterWorld Guest from 54.242.241.20
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
File renaming / reordering
Artie_J

5+ Year Member



 
Msg#: 4486347 posted 12:29 am on Aug 20, 2012 (gmt 0)

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

name-1.jpg
name-3.jpg
name-5.jpg

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

name-1.jpg
name-2.jpg
name-3.jpg


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

 

incrediBILL

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



 
Msg#: 4486347 posted 12:58 am on Aug 20, 2012 (gmt 0)

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.

$num=0;
$files = scandir( 'oldname*.jpg' );
while ($oldfile = current($files)) {
$num++;
$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!

Artie_J

5+ Year Member



 
Msg#: 4486347 posted 1:33 pm on Aug 20, 2012 (gmt 0)

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.

Artie_J

5+ Year Member



 
Msg#: 4486347 posted 8:13 pm on Aug 20, 2012 (gmt 0)

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

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

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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved