
php如何实现批量替换修改目录下所有文件

php如何实现批量替换修改目录下所有文件
-
- 满意回答

1.背景
某目录下很多文档,要批量替换某些字符串。
2.方案
先遍历所有文档,确定要修改文档的后缀,再替换字符串,下例也可用正则替换。
$path='/var/www/golang';
$search='test string';
$replace='';
$num=0;
if($handle = opendir($path)){
while(false !== $file=readdir($handle)){
if($file !='.' && $file !='..'){
if(is_dir($path.'/'.$file)){
file_list($path.'/'.$file);
}else{
if(preg_match ("/.html$/",$file)){//file type
file_content_replace($path.'/'.$file, $search, $replace);
echo ++$num.'.'.$file;
}else
echo $file.'-no file type-';
}//is_dir
}//file
}//withle
closedir($handle);
}//handle
function file_content_replace($filename, $search, $replace){
$string = file_get_contents($filename);
$new_string = str_replace($search, $replace, $string,$i);
//echo 'result:'.$i;
if($string !=$new_string) file_put_contents($filename, $new_string);
}//file-
3.备注
因为要写入内容,所以要确定文件、文件夹的权限,str_replace替换功能较弱,若是大段落替换,效果不佳。
提问者对回答的评价:
谢谢您的解答!
- QQ游戏军旗等级分布 (1个回答)
- 黑神话悟空最低需要多大的硬盘? (1个回答)
- fastorange是什么软件,可以卸载吗? (1个回答)
- ahsprotector是什么软件? (1个回答)
- 如何查询bios版本 (1个回答)
- win10系统右下角天气怎么关闭 (1个回答)
- elf.exe是什么文件? (1个回答)
- word怎么中文宋体,英文、数字设置Times New Roman (1个回答)
- 如何在Word中实现中文宋体,英文、数字Times New Roman (1个回答)
- python2报 ImportError: No module named google.proto (1个回答)
- 求寻道大千2025年最新可兑 ...
- 电脑出现 R6034 Runtime ...
- nvm use 后 node和npm均无 ...
- ‌AirPods保修期是多 ...
- 苹果A2564是什么型号耳机 ...
- 打开Mac版的PowerPoint都 ...
- error This project‘s p ...
- 使用javascript的网页是静 ...
- Centos7停止维护还能用吗 ...
- SSL证书使用的端口号通常 ...
- 此表单不安全,因此系统已 ...
- Tipask2.0(2.5)改SSL证书 ...
- 打开谷歌浏览器提示应用程 ...
- 咨询下赛博朋克2077配置要 ...
- windows2003网站迁移到wi ...
- 升级使用https协议后网站 ...
- 淘宝先用后付怎么关闭