2011-02-14 5 views
9

모든 이미지에 SKU # 단어가있는 폴더에 1000 개의 이미지가 있습니다. 예폴더의 파일 이름 바꾸기 - PHP

WV1716BNSKU#.zoom.1.jpg 
WV1716BLSKU#.zoom.3.jpg 

를 들어 내가 모든 파일 이름을 읽고 그래서 다음

WV1716BN.zoom.1.jpg 
WV1716BL.zoom.3.jpg 

에 이름을 파일 이름에서 SKU 번호를 제거하기 만하면, 그것은 PHP에 일괄 이름 변경을 할 수 있습니까?

<?php 

if ($handle = opendir('/path/to/files')) { 
    while (false !== ($fileName = readdir($handle))) { 
     $newName = str_replace("SKU#","",$fileName); 
     rename($fileName, $newName); 
    } 
    closedir($handle); 
} 
?> 

참고 :

+0

모든 파일의 이름을 바꾸는 루프와 같은 의미입니까? –

답변

1

이 작업을 완료하는 단계는 매우 간단하다 : fopen를 사용하여 각 파일을 통해

  • 반복 할 각 파일에 대한 readdir
  • 이 (
  • 새로운 직접 호출 이전에 기존 파일을 복사 세그먼트로 파일 이름을 구문 분석 정성적인 이유)
  • 루트 파일의 이름을 새 이름으로 바꿉니다.

작은 예 :

if ($handle = opendir('/path/to/images')) 
{ 
    /* Create a new directory for sanity reasons*/ 
    if(is_directory('/path/to/images/backup')) 
    { 
     mkdir('/path/to/images/backup'); 
    } 

    /*Iterate the files*/ 
    while (false !== ($file = readdir($handle))) 
    { 
      if ($file != "." && $file != "..") 
      { 
       if(!strstr($file,"#SKU")) 
       { 
        continue; //Skip as it does not contain #SKU 
       } 

       copy("/path/to/images/" . $file,"/path/to/images/backup/" . $file); 

       /*Remove the #SKU*/ 
       $newf = str_replace("#SKU","",$file); 

       /*Rename the old file accordingly*/ 
       rename("/path/to/images/" . $file,"/path/to/images/" . $newf); 
      } 
    } 

    /*Close the handle*/ 
    closedir($handle); 
} 
+0

이 스 니펫은 정상적으로 작동하지만 파일의 확장명도 변경되었습니다. 그것을 해결할 수 있습니까 ?? –

2

음, 반복자를 사용하여 :

class SKUFilterIterator extends FilterIterator { 
    public function accept() { 
     if (!parent::current()->isFile()) return false; 
     $name = parent::current()->getFilename(); 
     return strpos($name, 'SKU#') !== false; 
    } 
} 
$it = new SkuFilterIterator(
    new DirectoryIterator('path/to/files') 
); 

foreach ($it as $file) { 
    $newName = str_replace('SKU#', '', $file->getPathname()); 
    rename($file->getPathname(), $newName); 
} 

FilterIterator은 기본적으로 그들에 SKU#없이 모든 비 파일 및 파일을 필터링합니다. 케이크의

$it = new GlobIterator('path/to/files/*SKU#*'); 
foreach ($it as $file) { 
    if (!$file->isFile()) continue; //Only rename files 
    $newName = str_replace('SKU#', '', $file->getPathname()); 
    rename($file->getPathname(), $newName); 
} 
9

조각 :

foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f) 
    rename ($f, str_replace("SKU#", "", $f)); 
그런 다음 당신이 모든으로 반복되면, 새로운 GlobIterator를 사용하여 ...

또는 5.3+에를 새 이름을 선언하고 파일의 이름을 변경

(또는 $dir/*.jpg 숫자가 중요하지 않을 경우) 또한이 샘플 사용할 수 있습니다

+0

= 1로하면 더 간단합니다. 편집 :'array_filte'r 배열의 첫 번째 매개 변수를 가져옵니다. – diEcho

+0

glob는 일반적으로 디렉터리 반복보다 몇 배 느립니다. 따라서 파일이 많으면 고려해야 할 사항입니다. https://www.phparch.com/2010/04/putting-glob-to-the-test / – Picard

1

:

$directory = 'img'; 
$gallery = scandir($directory); 
$gallery = preg_grep ('/\.jpg$/i', $gallery); 
// print_r($gallery); 

foreach ($gallery as $k2 => $v2) { 
    if (exif_imagetype($directory."/".$v2) == IMAGETYPE_JPEG) { 
     rename($directory.'/'.$v2, $directory.'/'.str_replace("#SKU","",$v2)); 
    } 
}