我是php的新手。我试图从日志文件中删除与某个字符串值匹配的行。
下面是能够显示日志文件中匹配行的代码,但我想删除该行并附加日志文件的其余行。
以下是我的代码:
<?php
$searchthis = "mystring";
$matches = array();
$handle = @fopen("myfile.log", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
//show results:
print_r($matches);
?>
修改 日志文件中的行:
john abraham hml3
john abraham hml1
$ search_string ='hml3'
答案 0 :(得分:2)
功能
function search_and_delete($_file,$search_string){
$file = file($_file);
foreach ($file as $line_index => $line) {
if(strpos($line, $search_string) !== false){
unset($file[$line_index]);
break;
}
}
file_put_contents($_file, implode("",$file));
}
样本用法
search_and_delete("/var/a.txt","removing_line_conteins");
答案 1 :(得分:1)
制作文件行数组并选择所需内容
$searchthis = "mystring";
$matches = array();
$handle = file("myfile.log");
foreach ($handle as $buffer)
if(strpos($buffer, $searchthis) === FALSE)
$matches[] = $buffer;
//show results:
print_r($matches);