php Method of Modifying Specified File Suffix

  • 2021-07-21 07:33:42
  • OfStack

Due to the requirements of the project, it is necessary to modify the suffix of asp into php, because it is lazy to modify each one. I think php and Qt1 are all high-level languages, and 1 high-level language provides functions for adding, deleting and checking the obtained content. After 1 data search and code testing, summarized the PHP modified the specified file suffix method, and shared it with everyone.

Goal: Change the asp suffix in the current directory to php, without affecting other "suffix format files", and only for the "current folder", and do not modify the files of the folders contained in the current folder.

Specific function codes are as follows:


<?php 
function foreachDir($dirname)
{ 
if(!is_dir($dirname))
{
  echo "{$dirname} not effective dir";
  exit();
}
 $handle=opendir($dirname); // Open Directory 

while (($file = readdir($handle))!==false) // Read directory 
{ 
 if($file!="." && $file!='..')
 { 
  if(is_dir($dirname.$file))
 { 
  echo $dirname.$file."<br/>"; 
  //foreachDir($dirname.$file); // If the comment number is removed, the folder files in the folder will be modified recursively 
 }
  else
 { 
  echo "--".$dirname."/".$file."<br/>"; 
  $temp = substr($file, strrpos($file, '.')+1); // Get suffix format 
   if ($temp == "asp") 
   {
  $pos = strripos($file,'.'); // Get the location to the file name 
  $filename = substr($file,0,$pos); // Get the file name 
  rename($dirname.'/'.$file,$dirname.'/'.$filename.'.php'); // Replace with php Suffix format. 
   }
 } 
 } 
 } 
} 
foreachDir('../traverseMendFilename');
?>

Interested friends can test run and expand the perfect example of this article, I believe it will be helpful for everyone to learn PHP programming.

In addition: Attached are four ways to get file extension for your reference.


Related articles: