Home >Backend Development >PHP Problem >How to batch modify file names in php

How to batch modify file names in php

王林
王林Original
2020-04-27 15:45:473261browse

How to batch modify file names in php

Can be modified in batches through the rename() function.

Function introduction:

The rename() function is used to rename files or directories.

Syntax format:

rename(oldname,newname,context)

If successful, this function returns TRUE. On failure, returns FALSE.

Example code:

<?php
header("Content-type: text/html; charset=utf-8");
//利用PHP目录和文件函数遍历用户给出目录的所有的文件和文件夹,修改文件名称
function fRename($dirname){
 if(!is_dir($dirname)){
  echo "{$dirname}不是一个有效的目录!";
  exit();
 }
 $handle = opendir($dirname);
 $i = 1;
 while(($fn = readdir($handle))!==false){

  if($fn!=&#39;.&#39;&&$fn!=&#39;..&#39;){
      echo "<br>将名为:".$fn."\n\r";
      $curDir = $dirname.&#39;/&#39;.$fn;
   if(is_dir($curDir)){
      fRename($curDir);
   }else{
      $path = pathinfo($curDir);
      //改成你自己想要的新名字
      $newname = $path[&#39;dirname&#39;].&#39;/&#39;.$i.&#39;.&#39;.$path[&#39;extension&#39;];
      echo "替换成:".$i.&#39;.&#39;.$path[&#39;extension&#39;]."\r\n";
      rename($curDir,$newname);
      $i++;
   }
  }
 }
}
//给出一个目录名称可以是相对路径,也可以是绝对路径
fRename(&#39;img\Gastroenterology&#39;);
exit();
?>

Some result screenshots are as follows:

How to batch modify file names in php

##For more related tutorials, please pay attention to

php Chinese website.

The above is the detailed content of How to batch modify file names in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn