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