2016-09-27 65 views
0

我想让脚本进入文件夹'images',取出每个文件,剪下前四个字符并重新命名。在PHP中重命名文件?

PHP

<?php 
$path = './images/'; 

if ($handle = opendir($path)) 
{ 
    while (false !== ($fileName = readdir($handle))) 
    { 
     if($fileName!=".." && $fileName!=".") 
     { 
      $newName = substr($fileName, 4); 
      $fileName = $path . $fileName; 
      $newName = $path . $newName; 

      rename($fileName, $newName); 
     } 
    } 

    closedir($handle); 
} 
?> 

这是如何在图像文件夹中的文件被命名为:

0,78test-1.jpg 
0,32test-2.jpg 
0,43test-3.jpg 
0,99test-4.jpg 

,这就是我希望他们看起来像:

test-1.jpg 
test-2.jpg 
test-3.jpg 
test-4.jpg 

问题是脚本删除了第一个8,12或16个字符,而不是四个,因为我想要它!所以,当我执行它我的文件看起来像这样:

-1.jpg 
-2.jpg 
-3.jpg 
-4.jpg 

UPDATE

我还跟踪包,以确保我没有执行脚本多次。脚本只执行一次!

+0

'$了newName = SUBSTR($文件名,如图4所示,strlen的($文件名));'? – RamRaider

+0

嘿,谢谢你的答案,但它不工作。 – user3877230

+1

您的代码适用于我:-https://eval.in/650573 –

回答

1

方式略有不同,虽然基本与substr部分,则这个对本地系统测试工作的罚款。

$dir='c:/temp2/tmpimgs/'; 
$files=glob($dir . '*.*'); 
$files=preg_grep('@(\.jpg$|\.jpeg$|\.png$)@i', $files); 


foreach($files as $filename){ 
    try{ 

     $path=pathinfo($filename, PATHINFO_DIRNAME); 
     $name=pathinfo($filename, PATHINFO_BASENAME); 
     $newname=$path . DIRECTORY_SEPARATOR . substr($name, 4, strlen($name)); 

     if(strlen($filename) > 4) rename($filename, $newname); 

    } catch(Exception $e){ 
     echo $e->getTraceAsString(); 
    } 
} 
+0

非常感谢!它工作得很好,虽然我仍然困惑为什么我的方法不工作;) – user3877230

0

你可能想试试这个小功能。它会为你做的只是适当的重命名:

<?php 

    $path = './images/'; 

    function renameFilesInDir($dir){ 
     $files = scandir($dir); 

     // LOOP THROUGH THE FILES AND RENAME THEM 
     // APPROPRIATELY... 
     foreach($files as $key=>$file){ 
      $fileName = $dir . DIRECTORY_SEPARATOR . $file; 
      if(is_file($fileName) && !preg_match("#^\.#", $file)){ 
       $newFileName = preg_replace("#\d{1,},\d{1,}#", "", $fileName); 
       rename($fileName, $newFileName); 
      } 
     } 
    } 

    renameFilesInDir($path); 
0
<?php 
$path = './images/'; 

if ($handle = opendir($path)) 
{ 
    while (false !== ($fileName = readdir($handle))) 
    { 
     if($fileName!=".." && $fileName!=".") 
     { 

//change below line and find first occurence of '-' and then replace everything before this with 'test' or any keyword 
      $newName = substr($fileName, 4); 

      $fileName = $path . $fileName; 
      $newName = $path . $newName; 

      rename($fileName, $newName); 
     } 
    } 

    closedir($handle); 
} 
?>