需求:移除檔名中特定模式(如 [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() 原子操作。建議封裝為可配置模式、支援預覽模式、具備衝突檢測的通用工具類,應對各種大規模檔案整理需求。