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

yipeiwu_com6年前PHP代码库

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

需求描述:

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

代码实现:

方法一

<?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);
  }
}

方法二

<?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相关内容感兴趣的读者可查看本站专题:《php文件操作总结》、《PHP目录操作技巧汇总》、《PHP常用遍历算法与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《PHP网络编程技巧总结

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

相关文章

php 更新数据库中断的解决方法

即可解决: set_time_limit(900); 这个函数指定了当前所在php脚本的最大执行时间, 虽然设定值是900秒,实际上 最大执行时间=php.ini里的max_execut...

浅谈PHP中JSON数据操作

JSON,全称是JavaScript Object Notation。它是基于JavaScript编程语言ECMA-262 3rd Edition-December 1999标准的一种轻...

PHP在字符串中查找指定字符串并删除的代码

$a = "abcababa"; $count=strpos($a,"ab"); $str=substr_replace($a,"",$count,2); 输出结果:cababa 代码虽...

用php代码限制国内IP访问我们网站

利用淘宝的IP接口来判断IP,是否是国内的ip,是国内(CN)的就不允许访问。 $ip = $_SERVER['REMOTE_ADDR']; $content = file_get...

php实现的debug log日志操作类实例

本文实例讲述了php实现的debug log日志操作类。分享给大家供大家参考,具体如下: <?php class Tool { public static func...