代碼實現
<?php
function foreachDir($path) {
$handle = opendir($path);
if (!$handle) return false;
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') continue;
$full = $path . '/' . $file;
if (is_dir($full)) {
echo "$full<br/>";
foreachDir($full);
} else {
echo "--$full<br/>";
$pos = strrpos($file, '.');
if ($pos !== false) {
$base = substr($file, 0, $pos);
rename($full, $path . '/' . $base . '.JPG');
}
}
}
closedir($handle);
return true;
}
foreachDir('D:/xampp/htdocs/TNF2');
改進建議
- 增加副檔名過濾(如只處理
.jpg/.png/.gif)。
- 添加
dry-run 模式,先打印重命名計劃不實際執行。
- 使用
RecursiveDirectoryIterator (SPL) 替代手動遞歸,代碼更健壯。
- 注意大小寫敏感文件系統(Linux)下
.JPG 與 .jpg 視為不同文件。