最近接到一个需求,需要在一个项目下的文件中查找是否包含某个 字符串 ,如果有就将其替换。
问题是一个项目有多级目录,上千个文件,不可能挨个找啊,于是就想到用程序先查找出含有某个字符串的文件,再在这些文件中查找,这样总比挨个找强吧。有朋友就要问了,你能用程序查找文件为什么不批量替换呢?好家伙,敢这么干的要么是个人才,要么就是项目不重要。想想批量替换之后出现问题,还是得批量找,这种给自己制造问题的做法还是想想就好。
话不多说上程序:
查找文件类封装【保存文件为:FindWordInFile.php】:
private $notFind = '没有找到相关数据!!!';
private static $count = 0;//统计查询到的文件总数
private static $instace = null;
/**
* 构造器
*/
private function __construct() {}
private function __clone(){}
public static function getInstace(): object
{
if (empty(self::$instace)) {
self::$instace = new self();
}
return self::$instace;
}
/**
* 对外调用主方法
*
*/
public function findwordIndex($word, $path) {
if(empty($word) || empty($path))return;
echo "查询结果:
";
if (!($word && (is_file($path) || is_dir($path)))) {
echo $this->notFind;
return;
}
if (is_file($path) && file_exists($path)) {
$this->findwordInFile($word, $path);
} elseif (is_dir($path)) {
$this->findwordInDir($word, $path);
}
echo "
总文件数:".self::$count."
";
}
/**
* 查找文件中是否存在指定字串
* @param array $word 查询的字串 数组
* @param string $path 查询的路径 文件
*/
private function findwordInFile($word, $path) {
$file_content = file_get_contents($path);
foreach ($word as $c) {
$res = strpos($file_content, $c);
if ($res !== false) {
echo $path.'
';
self::$count++;
}
}
}
/**
* 查找目录下的文件中是否存在指定字串
* @param array $word 查询的字串 数组
* @param string $path 查询的路径 目录
*/
private function findwordInDir($word, $path) {
$file = scandir($path);
foreach ($file as $f) {
if (in_array($f, array('.','..'))) {
continue;
}
$file_path = $path.DIRECTORY_SEPARATOR.$f;
if (is_file($file_path)) {
$this->findwordInFile($word, $file_path);
} elseif (is_dir($file_path)) {
$this->findwordInDir($word, $file_path);
}
}
}
}
前端调用实现:
查找目录文件下是否存在特定字串
include "FindWordInFile.php";//载入类,小编就放在同个文件里就无需引入
//接收表单参数
$char = !empty($_POST['char']) ? explode('|',$_POST['char']) : '';
$path = !empty($_POST['path']) ? trim($_POST['path']) : '';
//调用查找方法
$obj = FindInFile::getInstace();
$obj->findwordIndex($word, $path);
?>
浏览器访问,结果输出:

好了,小伙伴们你们项目中批量替换是怎么干的,欢迎留言分享。
海报
0 条评论
195
相关文章
本站已关闭游客评论,请登录或者注册后再评论吧~