[SOLVED] Multiple files rename

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Multiple files rename

Post by tomfra »

Hi there,

I have been trying to solve one problem for some time but it looks like I am still far from the solution so perhaps someone could help a little. The problem is actually that I know very little about arrays still.

Here is what I need to do:

Let's say there are 3 files in a directory named:

something1.html
something2.html
something3.html

...and I want to rename them via php script to:

something_else1.html
something_else2.html
something_else3.html

Any ideas how to do this? I know how strip the number at the end and move it into array and vice versa but how do I accomplish that the script reads only the right files (filters them) from the directory ignoring the other files and then rename them to the new filename leaving the right number at the end?

I am still relatively new to php but have done some scripts already. My webhost's server has PHP 4.3.3.

Thanks for any ideas!

Tomas
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

perhaps something like this:

Code: Select all

foreach(glob('something[1-3].html') as $filename) {
   //rename() the file here
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

[php_man]glob[/php_man] or the [php_man]opendir[/php_man], [php_man]readdir[/php_man] combo. Combine that with either [php_man]move[/php_man] or the [php_man]fopen[/php_man], [php_man]fwrite[/php_man] combo...
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Another alternative:

Code: Select all

<?php
$filepath = $_SERVER['DOCUMENT_ROOT']; //or use a full path to where the files are
$oldname = 'something';
$newname = 'something_else';

foreach(glob($filepath.'/'.$oldname.'*.*') as $oldfile){
  $newfile = str_replace($oldname, $newname, $oldfile);
  echo 'Renaming '.$oldfile.' to '.$newfile.'<br />';
  rename($oldfile, $newfile);
}
?>
tomfra
Forum Contributor
Posts: 126
Joined: Wed Jun 23, 2004 12:56 pm
Location: Prague, Czech Republic

Post by tomfra »

Thanks for the super quick replies! :)

The solution from markl999 seems to be working just fine.

Thanks again, I am sure there will be more questions from me soon ;)

Tomas
Post Reply