首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 批量重命名檔案實戰腳本

     編輯:PHP 綜合知識

PHP 遞迴批量重命名檔案工具腳本

需求:移除檔名中特定模式(如 [1]),支援子目錄遞迴處理。本文提供完整可執行腳本與關鍵函數解析。

完整腳本



核心函數解析

遞迴掃描:getFileTree()

  • 使用 glob() 取得目錄內所有項目
  • is_dir() 判斷目錄,遞迴合併結果
  • 檔案直接加入陣列
  • 回傳扁平化的檔案路徑陣列

路徑處理

  • basename() 取得純檔名
  • dirname() 取得目錄路徑
  • DIRECTORY_SEPARATOR 跨平台相容

重命名邏輯

  • str_replace('[1]', '', $fileName) 移除目標字串
  • rename($old, $new) 執行重命名
  • 檢查新舊路徑不同避免無謂操作

進階擴充:通用模式替換

function batchRename($path, $patterns, $dryRun = false) {
    // $patterns = ['[1]' => '', 'old_' => 'new_', '/\s+/' => '_'];
    $files = getFileTree($path);
    foreach ($files as $filePath) {
        $fileName = basename($filePath);
        $newName = $fileName;
        foreach ($patterns as $search => $replace) {
            if ($search[0] === '/' && $search[strlen($search)-1] === '/') {
                // 正則模式
                $newName = preg_replace($search, $replace, $newName);
            } else {
                // 字串替換
                $newName = str_replace($search, $replace, $newName);
            }
        }
        if ($newName !== $fileName) {
            $newPath = dirname($filePath) . DIRECTORY_SEPARATOR . $newName;
            if (!$dryRun) {
                rename($filePath, $newPath);
            }
            echo ($dryRun ? "[預覽] " : "") . "$fileName → $newName\n";
        }
    }
}

// 使用
batchRename('/path/to/files', [
    '[1]' => '',
    '/\s+/' => '_',      // 空白替換底線
    '/^IMG_/' => 'photo_', // 前綴替換
], true); // true = 預覽模式

安全性檢查清單

風險防範措施
重命名衝突(同名檔案)檢查 file_exists($newPath),加入流水號後綴
誤刪重要檔案先執行預覽模式,確認無誤再實際執行
權限不足檢查目錄寫入權限,捕捉 rename 失敗
編碼問題確認檔案系統編碼與 PHP 腳本編碼一致(UTF-8)

總結

PHP 批量重命名核心在於 glob() 遞迴掃描 + rename() 原子操作。建議封裝為可配置模式、支援預覽模式、具備衝突檢測的通用工具類,應對各種大規模檔案整理需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved