您的位置 首页 php

php之多级目录下查找文件中是否含有某个字符串功能实现

最近接到一个需求,需要在一个项目下的文件中查找是否包含某个 字符串 ,如果有就将其替换。

问题是一个项目有多级目录,上千个文件,不可能挨个找啊,于是就想到用程序先查找出含有某个字符串的文件,再在这些文件中查找,这样总比挨个找强吧。有朋友就要问了,你能用程序查找文件为什么不批量替换呢?好家伙,敢这么干的要么是个人才,要么就是项目不重要。想想批量替换之后出现问题,还是得批量找,这种给自己制造问题的做法还是想想就好。

话不多说上程序:

查找文件类封装【保存文件为:FindWordInFile.php】:

 <?php
/**
 * 多级目录下查找文件中是否存在指定字串
 * @autor 蓝梦时醒
 * @date 2022-05-21
 */class FindInFile {

 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 "<h3>查询结果:</h3><br/>";
 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 "<br/><br/><h5>总文件数:".self::$count."</h5>";
}

/**
 * 查找文件中是否存在指定字串
 * @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.'<hr/>';
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);
}
}
}
}  

前端调用实现:

 <!DOCTYPE html>
<html>
<head>
<title>查找目录文件下是否存在特定字串</title>
</head>
<body>
<form action="" method="post">
查找的字串:<input type="text" name="char" value="" />
( <font color="red">notes:查找多个字串请用竖线“|”分割</font> )<br/><br/>
查找的路径:<input type="text" name="path" value="" /><br/><br/>
<input type="submit" value="查询"><br/><br/>
</form>
 <?php
//  include  "FindWordInFile.php";//载入类,小编就放在同个文件里就无需引入
 //接收表单参数
$char = !empty($_POST['char']) ? explode('|',$_POST['char']) : '';
$path = !empty($_POST['path']) ? trim($_POST['path']) : '';

//调用查找方法
$obj = FindInFile::getInstace();
$obj->findwordIndex($word, $path);
?>
</body>
</html>  

浏览器访问,结果输出:

好了,小伙伴们你们项目中批量替换是怎么干的,欢迎留言分享。

文章来源:智云一二三科技

文章标题:php之多级目录下查找文件中是否含有某个字符串功能实现

文章地址:https://www.zhihuclub.com/77583.shtml

关于作者: 智云科技

热门文章

网站地图