2016-11-17 11 views
0

私のようなファイルを含むいくつかのディレクトリがあります。そのディレクトリ名とファイル名を変更

folder1/filename.jpg 
folder2/filename.pdf 
folder3/filename.jpg 

をそして私はそれに対応するディレクトリ名を持つすべてのディレクトリ内のすべてのファイルの名前を変更したい(が、その拡張子を維持する)のように、:

folder1/filename.jpg to folder1/folder1.jpg 
folder2/filename.pdf to folder2/folder2.pdf 
folder3/filename.jpg to folder3/folder3.jpg 

編集:また、名前を変更したすべてのファイルを別のディレクトリ(「allfiles」など)にコピーしたいとします。

a similar question in Perl languageが見つかりました。

PHPでどのように実現できますか?

+0

を質問:S ... – Asfo

+0

あなたはこれまで何をしていますか? –

答えて

2

ここであなたがそれを行うための方法を持っている:

<?php 

// Array with all subdirectories in directory 
$dirArray = array_filter(glob('/path/to/directory/*'), 'is_dir'); 

// $dir is the path to the subdirectory 
foreach ($dirArray as $dir) { 

    // $dirName has the future name of files in that subdirectory 
    $dirName = basename($dir); 

    // Take all the elements in the subdirectory (except '.' and '..') 
    $filesArray = array_diff(scandir($dir), array('.', '..')); 

    $i = 0; 
    foreach ($filesArray as $file) { 
     // Take the file extension for the rename method 
     $fileExtension = pathinfo($file, PATHINFO_EXTENSION); 

     $oldName = $dir . "/" . $file; 
     $newName = $dir . "/" . $dirName . "-" . $i . "." . $fileExtension; 

     rename($oldName, $newName); 
     $i++; 
    } 
} 

、あなたが$newNameに次の行を使用することができ、各サブディレクトリに一つだけのファイルがあります確信している場合:これはない

$newName = $dir . "/" . $dirName . "." . $fileExtension; 
+0

多くのありがとう、それは私が探しているものです。名前を変更したすべてのファイルを別のフォルダにコピーする方法を教えてください。 – Sifur

+0

コピーまたは移動しますか? @Sifur – nanocv

+0

元のファイルをそのままコピーして保管してください。 – Sifur

関連する問題