You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP递归修改目录及子目录下的文件扩展名

PHP递归修改多级目录下的.pdf.pdf文件扩展名

可以用递归遍历目录的方式批量处理这类文件,以下是直接可用的实现代码:

<?php
function renamePdfFiles($dir) {
    $dh = opendir($dir);
    if (!$dh) return;

    while (($file = readdir($dh)) !== false) {
        if ($file === '.' || $file === '..') continue;

        $fullPath = $dir . DIRECTORY_SEPARATOR . $file;

        if (is_dir($fullPath)) {
            renamePdfFiles($fullPath);
            continue;
        }

        // 匹配小写后缀的.pdf.pdf,兼容大小写差异
        if (strtolower(substr($file, -8)) === '.pdf.pdf') {
            $newName = substr($fullPath, 0, -4);
            if (rename($fullPath, $newName)) {
                echo "已重命名:$fullPath -> $newName\n";
            } else {
                echo "重命名失败:$fullPath\n";
            }
        }
    }

    closedir($dh);
}

// 替换为你的项目根目录绝对路径
$targetDir = '/var/www/html/your-project-root';
renamePdfFiles($targetDir);
?>

关键细节说明

  • 递归遍历:函数会自动处理所有子目录,无需手动指定层级
  • 兼容性处理:用DIRECTORY_SEPARATOR替代硬编码的/,保证代码在不同系统下都能运行;strtolower避免因文件名大小写(如.PDF.PDF)导致的匹配失败
  • 安全验证:跳过.和..目录,避免无限循环

执行前必看

  1. 备份文件:先对目标目录做完整备份,防止重命名出错导致数据丢失
  2. 权限检查:确保运行PHP的用户(LAMP环境下通常是www-data)对目标目录和文件拥有读写权限
  3. 测试先行:可以先注释掉rename($fullPath, $newName)这一行,只打印重命名计划,确认无误后再执行实际重命名

内容的提问来源于stack exchange,提问作者Don Britton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 06:38:19