2016-09-27 8 views
0

スクリプトを 'images'フォルダに入れ、すべてのファイルを取り出し、最初の4文字を切り取り、名前を変更します。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文字を切り捨てることです。私はそれがほしいと思う4つ!私はそれを実行したときので、私のファイルは、次のようになります。

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

UPDATE私はまた、私はスクリプトを複数回実行するわけではないことを確認するために、パッケージを追跡し

。スクリプトは一度だけ実行されます!

+0

'$ newnameの= SUBSTR($ fileNameに、4、strlenを($ファイル名));'? – RamRaider

+0

お返事ありがとうございますが、動作していません。 – user3877230

+1

あなたのコードは私にとって役に立ちます:-https://eval.in/650573 –

答えて

1

A、わずかに異なるアプローチを。

$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

この小さな機能を試してみるとよいでしょう。それはあなたのためだけの適切な名前の変更を行うだろう。これは、ローカルシステム上のテストのためにうまく働いsubstr一部と本質的に同じものの

<?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); 
} 
?> 
関連する問題