search
HomeBackend DevelopmentPHP Tutorial写了个遍历目录、批量替换文件内容的类

之前有需要,就写了这个类。
功能:
1 遍历目录下的所有文件(可指定后缀名)
2 批量替换文件内容(正则、字符串)
3 批量替换文件后缀名
4 批量替换文件编码

使用例:

$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;		}		return true;	}	/*	*  字符串替换文件内容(忽略大小写)、编码、后缀名        */	function modifyFileBy_ireplace($search, $replace, $in_charset='', $out_charset='', $in_extension='', $out_extension=''){		//不贴了 和上面的modifyFileBy_replace一样 只是用str_ireplace替换而已	}	/*	*  正则替换文件内容(忽略大小写)、编码、后缀名	*	*  Parameters:	*  	1 search:	需要替换内容的正则表达式	*  	2 replace:	替换后的字符串	*  	3 in_charset:	原编码	*  	4 out_charset:	新编码	*  	5 in_extension:	原后缀名	*  	6 out_extension:新后缀名	*  Return:	*  	true or false        */	function modifyFileBy_regex($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;		}		if(preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) {			/* remove eval-modifier from $search */			$search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]);		}		foreach($this->dirPath_array as $key=>$file) {			$content = file_get_contents($file);//read contents			$content = preg_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;		}		return true;	}	/*	*  变换编码	*	*  Parameters:	*  	1 in_charset:	原编码	*  	2 out_charset:	新编码	*  	3 flag:		0对遍历得到的文件转换编码 1对指定内容转换编码	*  	4 content:	仅在flag为1时使用	*  Return:	*  	true or false        */	function changeCharset($in_charset='', $out_charset='', $flag=0, &$content=''){		/* input check */		if (strlen($in_charset)==0 || strlen($out_charset)==0){			return false;		}		if($flag == 0){			/* 对遍历得到的文件转换编码 */			foreach($this->dirPath_array as $file) {				$content = file_get_contents($file);//read contents				/* change the encode */				$content = iconv($in_charset, $out_charset, $content);				unlink($file);				file_put_contents($file, $content);				unset($content);			}		}else{			/* 对指定内容转换编码 */			if(strlen($content) != 0){				$content = iconv($in_charset, $out_charset, $content);			}		}		return true;	}	/*	*  变换后缀名	*	*  Parameters:	*  	1 in_extension:		原后缀名	*  	2 out_extension:	新后缀名	*  	3 flag:			0对遍历得到的文件变换后缀名 1对指定文件名变换后缀名	*  	4 fileName:		仅在flag为1时使用	*  Return:	*  	true or false        */	function changeExtension($in_extension='', $out_extension='', $flag=0, &$fileName=''){		/* inout check */		if(strlen($in_extension)==0 || strlen($out_extension)==0){			return false;		}		if($flag == 0){			/* 对遍历得到的文件变换后缀名 */			foreach($this->dirPath_array as $key=>$file) {				/* change file's extension */				$tmp = explode('.',$file);				$nowExtension = array_pop($tmp);				if($nowExtension == $in_extension){					$content = file_get_contents($file);//read contents					unlink($file);					$file = implode('.',$tmp).'.'.$out_extension;					file_put_contents($file, $content);					unset($content);				}				/* 更新遍历文件名结果集 */				$this->dirPath_array[$key] = $file;			}		}else{			/* 对指定文件名变换后缀名 */			if(strlen($fileName) != 0){				$tmp = explode('.',$fileName);				$nowExtension = array_pop($tmp);				if($nowExtension == $in_extension){					$fileName = implode('.',$tmp).'.'.$out_extension;				}			}		}		return true;	}}


回复讨论(解决方案)

这个很强大,学习了~

lz你太伟大了。。。。。。。。

加分加分加分

不错

不过有些还是不规范
比如:modifyFileBy_replace 一时驼峰式,一时下划线分隔式

公用函数没用使用 public 
私有函数开头应该以 _ 开头

不错

不过有些还是不规范
比如:modifyFileBy_replace 一时驼峰式,一时下划线分隔式

公用函数没用使用 public 
私有函数开头应该以 _ 开头
对  
是不太规范 

是很不规范!!!

  private function openDir($dirPath_target) 
  private function closeDir($dirHander) 
这两个方法没有必要存在,在里面也只是调用原生的函数

建议在 递归方法(getDirExplorer)中回调工作方法,而不是构造整个目录树后再用工作函数处理。
并不是什么时候都需要返回目录树的,比如你的应用只是替换文件内容


学习了.

ftgyhu

是很不规范!!! 好像是这样

  private function openDir($dirPath_target) 
  private function closeDir($dirHander) 
这两个方法没有必要存在,在里面也只是调用原生的函数

建议在 递归方法(getDirExplorer)中回调工作方法,而不是构造整个目录树后再用工作函数处理。
并不是什么时候都需要返回目录树的,比如你的应用只是替换文……
打算重写的时候去掉这两个方法
工作方法的话,主要是希望这个类有一定通用性
例子中的函数有点功能大杂烩的味道、一次遍历把文本替换、编码、后缀名改变都执行了。但实际中也有可能只希望变换编码或者后缀,所以这两个其实是分别单独作为2个功能提供的。所以考虑把遍历和各功能分开来,自由选择调用。

打算加个__get,在任一个功能被执行完毕后,可随时返回最新的遍历结果集合。

不错学习下~

好的,谢谢!!!

学习一下

这个很强大,学习了~

学习。

突然发现我进错板块了 OMG

很好!学习了。

good!

引用 4 楼 yangball 的回复:

不错

不过有些还是不规范
比如:modifyFileBy_replace 一时驼峰式,一时下划线分隔式

公用函数没用使用 public
私有函数开头应该以 _ 开头

对  
是不太规范
不管规范不规范,写出来就很强了,能写出来的有多少?

服务吧

本帖最后由 xuzuning 于 2011-06-24 13:44:35 编辑

 /*    *  遍历指定目录,返回其下的文件名集合    *    *  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;    }

好东西

yidingdianer,yebucuo,bucuo

学习了。。

呵呵不错,用glob可能会减少一些代码
这些功能其实比较常见,linux下会比较轻松,3,4行shell估计就可以搞定了

先慨叹一下,因为我写不出,没那个耐心


后问一个问题:

为什么不用SPL?
用SplFileInfo、SplFileObject和迭代器应该更好

另外,php处理windows下unicode的文件名还是死症,只能期待php开发者提高,所以目前代码必须考虑这个问题

耐心看完了。写得不错!

不过有些代码的效率应该可以再提高些,

比如end(explode('.',$fileName));如果改成substr(strrchr($fileName,'.'),1) ,这个也许效率会更高些!

不过有些代码的效率应该可以再提高些,

比如end(explode('.',$fileName));如果改成substr(strrchr($fileName,'.'),1) ,这个也许效率会更高些!
啊  对的
谢谢你的指教 重写的时候再优化一下 

先慨叹一下,因为我写不出,没那个耐心


后问一个问题:

为什么不用SPL?
用SplFileInfo、SplFileObject和迭代器应该更好

另外,php处理windows下unicode的文件名还是死症,只能期待php开发者提高,所以目前代码必须考虑这个问题
谢谢指教
SplFileInfo、SplFileObject不了解  周末看看

没有看到我期望的功能,比如文件自动侦测编码,然后转换为目标编码...


楼主很强大,我以前也准备搞个的,想想算了,没那个时间.

给点积分吧

mark

hao 

不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂不懂

多多学习吧

一个rename 就能解决啊

好东东
谢谢分享

学习,谢谢楼主~~

没看懂

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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version