PHP实现批量修改文件名的方法示例

时间:2022-11-08 18:02:12

本文实例讲述了PHP实现批量修改文件名的方法。分享给大家供大家参考,具体如下:

需求描述:

某个文件夹下有100个文件,现在需要将这个100个文件的文件名后添加字符串Abc(后缀名保持不变)。

代码实现:

方法一

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$dir = __DIR__."\image\\";
$list = scandir($dir);
foreach ($list as $item) {
  if(!in_array($item,['.','..'])){
    $arr = explode(".", $item);
    $origin_name = reset($arr);
    $new_name = $origin_name.'Abc.'.end($arr);
    $origin_path = $dir.$item;
    $data = file_get_contents($origin_path);
    $new_path = $dir.$new_name;
    $res[] = file_put_contents($new_path, $data);
    unlink($origin_path);
  }
}

方法二

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$dir = __DIR__."\image\\";
$list = scandir($dir);
foreach ($list as $item) {
  if(!in_array($item,['.','..'])){
    $arr = explode(".", $item);
    $origin_name = reset($arr);
    $new_name = $origin_name.'Abc.'.end($arr);
    $origin_path = $dir.$item;
    $new_path = $dir.$new_name;
    copy($origin_path, $new_path);
    unlink($origin_path);
  }
}

方法二使用了copy函数,更加简便。

文件目录要有写入权限才行

希望本文所述对大家PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/koastal/article/details/52084412