WD1X.COM - 问答一下,轻松解决,电脑应用解决专家

您好,欢迎来问答一下![登录] [注册]


已解决问题数:10040
待解决问题数:17
今天,你遇到了什么技术难题?我要提问
页面导航:问答一下 > 软件专家问答
  • 已解决
匿名用户
112.12.134.*

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

解决时间 解决时间:2024/01/28 13:39   热度:223

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

  • 满意答案
  • 满意回答
头像
WD1X专家团
回答于:2023/09/12 11:36

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替换功能较弱,若是大段落替换,效果不佳。

提问者对回答的评价:

谢谢您的解答!

支持  反对 

支持(0) 反对(0)
其他回答 (共0条)
关于我们 | 版权声明 | 网站导航 | Tag标签 |
Copyright © 2021-2022 WD1X.Com Inc All Rights Reserved.