逐行处理并截取数据后二次指定字符串截取写入新文件
<?php
/**
* 逐行处理并截取数据后二次指定字符串截取写入新文件
*/
class FileProcess
{
/**
* FileProcess constructor.
* @param $path 文件路径
* @param $newPath 生成的日志文件路径
* @param $subOneNum 第一次行处理并截取的长度
* @param $subOneNum 第一次行处理并截取的字符串
* @param $startTwoSub 第二次截取开始字符串
* @param $endTwoSub 第二次截取结束字符串
* @param $subTwoString 第二次截取的字符串
*/
public static function Process($path, $newPath, $subOneNum, $subOneString, $startTwoSub, $endTwoSub, $subTwoString)
{
ini_set('max_execution_time', '0');
$file = fopen($path, "r") or exit("Unable to open file!");
$startTime = microtime(true);
while (!feof($file)) {
$line = fgets($file);
$rowStr = substr($line, 0, $subOneNum);
if ($rowStr == $subOneString) {
//再指定截取的两个字符串之间的字符再写入文件
$res = self::getBetween($line, $startTwoSub, $endTwoSub);
if ($res == $subTwoString) {
file_put_contents($newPath, $line, FILE_APPEND);
echo $line;
}
}
}
$totalTime = microtime(true) - $startTime;
echo "执行完毕,共计耗时---" . $totalTime;
fclose($file);
}
/**
* @param $input
* @param $start
* @param $end
* @return false|string
* 再指定截取的两个字符串之间的字符
*/
public static function getBetween($input, $start, $end)
{
$substr = substr($input, strlen($start) + strpos($input, $start), (strlen($input) - strpos($input, $end)) * (-1));
if (!empty($substr)) {
return $substr;
}
}
}
$path = "www8001-error.log";
$subTwoString = "bme-test-svc";
$newPath = $path.$subTwoString."-log-0320.txt";
$subNum = 12;
$subOneString = "[20-Mar-2021";
$startTwoSub = "/home/data/webroot/";
$endTwoSub = "/protect";
FileProcess::Process($path, $newPath, $subNum, $subOneString, $startTwoSub, $endTwoSub, $subTwoString);
大海技术博客:http://www.ypyunedu.com/article/159