早上有个站需要全站查找替换,结果文件太多,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 "全部替换成功";
}
|