Page 1 of 1

Multiple files rename

Posted: Wed Jun 23, 2004 12:56 pm
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

Posted: Wed Jun 23, 2004 1:01 pm
by Weirdan
perhaps something like this:

Code: Select all

foreach(glob('something[1-3].html') as $filename) {
   //rename() the file here
}

Posted: Wed Jun 23, 2004 1:03 pm
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...

Posted: Wed Jun 23, 2004 1:05 pm
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);
}
?>

Posted: Wed Jun 23, 2004 1:20 pm
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