php写的查找和替换一个文件夹下所有的文件内容

早上有个站需要全站查找替换,结果文件太多,DW替换不完,于是用PHP写了一个

1、获取目录下的所有文件

/****************************
	* 获取目录下的所有文件
	* [$dir] 文件夹路径
	****************************/
	function deepScanDir($dir) {
		$fileArr = array ();
		$dirArr = array ();
		$dir = rtrim($dir, '//');
		if (is_dir($dir)) {
			$dirHandle = opendir($dir);
			while (false !== ($fileName = readdir($dirHandle))) {
				$subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
				if (is_file($subFile)) {
					$fileArr[] = $subFile;
				}
				elseif (is_dir($subFile) && str_replace('.', '', $fileName) != '') {
					$dirArr[] = $subFile;
					$arr = $this->deepScanDir($subFile);
					$dirArr = array_merge($dirArr, $arr['dir']);
					$fileArr = array_merge($fileArr, $arr['file']);
				}
			}
			closedir($dirHandle);
		}
		return array (
			'dir' => $dirArr,
			'file' => $fileArr
		);
	}



2、循环对每个文件进行查找和替换

/*
	* 替换成APP中可用的路径,在web文件夹中
	*/
	public function ok_web(){
		//查找字符
		$yuanlai = array(
			'"/resources/',
			'"/uploads/',
			'"/web/',
			'href="/"',
			'/web',
			'typedir+\'/\'+v.aid+"',
			'v.litpic',
		);
		//替换字符
		$tihuan = array(
			'"../resources/',
			'"../uploads/',
			'"',
			'href="../index.html"',
			'',	
			'v.aid+"',
			'".."+v.litpic'	
		);
		
		//查找的文件夹
		$dir = WEBROOT.'/app/web';
		//获取文件
		$dirs = $this->deepScanDir($dir);
		//文件字符串替换
		foreach($dirs['file'] as $file){
			$file = 'G:\hospital\hospital\admin/app/web\yiyuanzhuanjia.html';
			$txt = file_get_contents($file);
			$txt =  str_replace($yuanlai,$tihuan,$txt);
			file_put_contents($file,$txt);echo $txt;exit;
		}
		$this->success('内页替换完成,下面替换首页',U('Json/ok_index'));	
	}
	
	/*
	* 替换成APP中可用的路径,在首页中
	*/
	public function ok_index(){
		//查找字符
		$yuanlai = array(
			'"/resources/',
			'"/uploads/',
			'"/web/',
			'href="/"',
		);
		//替换字符
		$tihuan = array(
			'"resources/',
			'"uploads/',
			'"web/',
			'href="index.html"',
		);		
		
		$file = WEBROOT.'/app/index.html';
		$txt = file_get_contents($file);
		$txt =  str_replace($yuanlai,$tihuan,$txt);
		file_put_contents($file,$txt);
		echo "全部替换成功";		
	}



转载于:https://my.oschina.net/tongjh/blog/192238

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值