天天看點

使用php修改指定檔案字尾

最近要将asp字尾的修改成php,因懶于一個個修改。又覺得php跟Qt一樣都是進階語言了,一般進階語言都有提供對獲得的内容進行增删改查的函數。于是乎,就上網搜了下,還真不少,故些将所用心得總結下來。

目标:将目前目錄下的asp字尾改成php,而不影響其它“字尾格式的檔案”,而且隻是針對“目前檔案夾”,對目前檔案夾内包含的檔案夾的檔案不進行修改。

  代碼如下:

<?php 
function foreachDir($dirname)
{ 

 if(!is_dir($dirname))
	 {
	  echo "{$dirname} not effective dir";
	  exit();
	 }
 $handle=opendir($dirname); //打開目錄

while (($file = readdir($handle))!==false)  //讀取目錄
{ 
	if($file!="." && $file!='..')
	{ 
	  if(is_dir($dirname.$file))
		{ 
			echo $dirname.$file."<br/>"; 
			//foreachDir($dirname.$file);  //如果注釋号去掉,将會遞歸修改檔案夾内的檔案夾檔案
		}
	  else
		{ 
			echo "--".$dirname."/".$file."<br/>"; 
			 $temp = substr($file, strrpos($file, '.')+1);  //擷取字尾格式
		    if ($temp == "asp")	
			   {
				$pos = strripos($file,'.');  //擷取到檔案名的位置
				$filename = substr($file,0,$pos);  //擷取檔案名
				rename($dirname.'/'.$file,$dirname.'/'.$filename.'.php'); //替換為php字尾格式。
			  }

		} 
	} 
 } 

} 
	 
foreachDir('../traverseMendFilename');
?>
           

另外:附上擷取檔案擴充名的四種方法: http://www.jb51.net/article/29765.htm