簡體   English   中英

使用數字重命名目錄中的所有文件

[英]Rename all files in a directory with numbers

我想知道是否有人可以幫助我為我編寫一個PHP腳本,重命名序列中目錄中的所有文件。

所以...

  • DSC_10342.JPG - > 1.JPG
  • DSC_10343.JPG - > 2.JPG
  • DSC_10344.JPG - > 3.JPG

    等等。

這是我的版本:

// open the current directory (change this to modify where you're looking)
$dir = opendir('.');

$i = 1;

// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
    // if the extension is '.jpg'
    if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
    {
        // do the rename based on the current iteration
        $newName = $i . '.jpg';
        rename($file, $newName);

        // increase for the next loop
        $i++;
    }
}

// close the directory handle
closedir($dir);

使用重命名重命名文件。 您可以使用這個方便的腳本遍歷目錄中的所有文件:

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

然后,只需查看文件名( $file )並確定要給出的數字。 如果您需要更多幫助,請告訴我,我會提供更多詳細信息。

試試這個:

$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
        rename($directory."/".$file, $directory."/".$index.".JPG");
        $index++;
    }

}
closedir($handler);

使用某人的代碼片段,它看起來像這樣:

<?php
$path = '.';
$i = 1;
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && is_file($path.'/'.$file)) {
            $oldname   = $path.'/'.$file;
            $path_info = pathinfo($oldname);
            rename($oldname, $path.'/'.($i++).'.'.$path_info['extension']);
        }
    }
    closedir($handle);
}
?>

它將重命名具有所有擴展名的文件,並跳過可能位於目錄中的目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM