详情页

php批量替换指定文件夹里面文件名字

时间:2023年10月04日

编辑:佚名

以下是一个可以实现批量重命名指定文件夹下文件名的 PHP 函数:
function batchRenameFiles($dir, $search, $replace) {
  $files = scandir($dir); // 获取目录下所有文件
  foreach ($files as $file) {
    $filePath = $dir . DIRECTORY_SEPARATOR . $file;
    // 排除 "." 和 ".." 以及目录
    if ($file == '.' || $file == '..' || is_dir($filePath)) {
      continue;
    }
    // 检查文件名是否包含搜索字符串
    if (strpos($file, $search) !== false) {
      $newName = str_replace($search, $replace, $file); // 构造新文件名
      // 检查新文件名是否已存在
      if (file_exists($dir . DIRECTORY_SEPARATOR . $newName)) {
        echo "文件 $newName 已存在,跳过文件 $file。\n";
      } else {
        // 进行文件重命名
        if (rename($filePath, $dir . DIRECTORY_SEPARATOR . $newName)) {
          echo "重命名文件 $file 为 $newName 成功。\n";
        } else {
          echo "重命名文件 $file 为 $newName 失败。\n";
        }
      }
    }
  }
}
该函数接受三个参数:
$dir: 要批量重命名文件的目录路径。
$search: 要查找和替换的字符串。
$replace: 要替换成的字符串。
函数通过使用 scandir 函数来获取指定目录下的所有文件,然后对每个文件进行判断,如果文件名包含搜索字符串,则构造新文件名并进行重命名操作。在重命名操作中,函数还会检查新文件名是否已经存在,以避免重名问题。
你可以通过以下方式调用该函数:
batchRenameFiles('/path/to/directory', 'old_string', 'new_string');
其中,/path/to/directory 是要批量重命名的目录路径,old_string 是要查找和替换的字符串,new_string 是要替换成的字符串。
成功后的效果图:

输出自己可以美化一下,也就加个br
相关文章
猜你需要