2016-09-27 69 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); 
} 
?>