Jump to content

renaming files form on local pc


hyster

Recommended Posts

I wrote this script to rename my many tv series I have on my pc, works by finding a string in the file name and replacing it

the script works fine until I want to replace the file name with something that is also in the path

file = band ep01.avi

path = j:\media\ TV shows\Band of Brothers\

 

so if I try to change "Band" to "Band of Brothers" the path changes as well 

is there a way I can change the code so it dosent effect the path ??

<?php

$path = 'J:\media\TV shows\Band of Brothers';

foreach(glob($path.'/*.*') as $filename){         
              echo $filename."</BR>";
}

?> 
 <table align="center" width="200px" border="0" cellspacing="1" cellpadding="3">
 <form name="form1" method="get" action="mov.php">
 <tr>
 <td colspan="3"><strong> </strong></td>
 </tr>
 <tr>
 <td width="71">Replace</td>
 <td width="6">:</td>
 <td width="301"><input name="rep" type="text" id="rep"></td>
 </tr>
 <tr>
 <td>With</td>
 <td>:</td>
 <td><input name="with" type="text" id="with"></td>
 </tr>
 <tr>
 <tr>
 <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
 </tr></form>
 </table>
 
<?php
                if (isset($_GET["rep"])) {
                $rep1=$_GET['rep'];
                }
                if (isset($_GET["with"])) {
                $with1=$_GET['with'];
                }
                
                
 foreach(glob($path.'/*.*') as $filename){        
              $strip =  str_replace($rep1, $with1, $filename);
              echo $strip."</br>";  
              rename($filename,$strip);
}
    
?>
Link to comment
https://forums.phpfreaks.com/topic/290285-renaming-files-form-on-local-pc/
Share on other sites

You'll need to separate the path of the file from the name of the actual file, and just change the name.

 

With the following method, you can get the file name only:

$filePath = '/usr/local/test.txt';
$file = basename($filePath);
echo $file; // should give test.txt

And, with the following, you can extract the directory name:

$filePath = '/usr/local/test.txt';
$dir = dirname($filePath);
echo $dir; // should give /user/local

dirname official doc

basename official doc

Or with path info, even better (as suggested by @ginerjm)

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

Code from the example in the official doc: http://php.net/manual/en/function.pathinfo.php

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.