日期:2014-05-17 浏览次数:20650 次
$dirExplorer = new DirExplorerClass(); $dirExplorer->getDirExplorer('D:/test1/test2/'); //遍历目录D:/test1/test2/ $dirExplorer->modifyFileBy_replace('aa','QQ','shift-jis','UTF-8','txt','TXT'); //将所有文件内容中的aa替换为QQ,文件编码从shift-jis转换为UTF-8,将所有txt的后缀名改为TXT
class DirExplorerClass{ var $dirPath_array = array();//遍历文件结果集合 function __construct(){ //donothing } /* * return a directory handle or die */ private function openDir($dirPath_target) { if (is_dir($dirPath_target)) { return opendir($dirPath_target); }else { die("$dirPath_target is Not a Directory"); } } /* * close a directory handle */ private function closeDir($dirHander) { closedir($dirHander); } /* * 遍历指定目录,返回其下的文件名集合 * * Parameters: * 1 dirPath:需要遍历的文件夹 * 2 extension:只返回指定后缀名的文件 * Return: * 遍历文件结果集合 */ function getDirExplorer($dirPath,$extension=''){ $dirHander=$this->openDir($dirPath); while($fileName = readdir($dirHander)){ if($fileName !='.' && $fileName !='..'){ $path = $dirPath."/" . $fileName; if(is_dir($path)){ $this->getDirExplorer($path); }else{ if(isset($extension) && $extension != ''){ $fileExtension = end(explode('.',$fileName)); if($fileExtension != $extension){ continue; } } $this->dirPath_array[]=$path; } } } $this->closeDir($dirHander); return $this->dirPath_array; } /* * 字符串替换文件内容(区别大小写)、编码、后缀名 * * Parameters: * 1 search: 需要替换的字符串 (数组可) * 2 replace: 替换后的字符串 (数组可) * 3 in_charset: 原编码 * 4 out_charset: 新编码 * 5 in_extension: 原后缀名 * 6 out_extension:新后缀名 * Return: * true or false */ function modifyFileBy_replace($search, $replace, $in_charset='', $out_charset='', $in_extension='', $out_extension=''){ /* input check */ if( !isset($search) || !isset($replace) || (strlen($in_charset)!=0 && strlen($in_charset)==0) || (strlen($in_charset)==0 && strlen($in_charset)!=0) || (strlen($in_extension)!=0 && strlen($out_extension)==0) || (strlen($in_extension)==0 && strlen($out_extension)!=0) ){ return false; } foreach($this->dirPath_array as $key=>$file) { $content = file_get_contents($file);//read contents $content = str_replace($search, $replace, $content); if(strlen($in_charset)!=0 && strlen($out_charset)!=0){ /* change the encode */ $this->changeCharset($in_charset, $out_charset, 1, $content); } unlink($file); if(strlen($in_extension)!=0 && strlen($out_extension)!=0){ /* change file's extension */ $this->changeExtension($in_extension, $out_extension, 1, $file); } file_put_contents($file, $content); unset($content); /* 更新遍历文件名结果集 */ $this->dirPath_array[$key] = $file; }