使用 strcmp 防止重复的日志行
我使用下面的代码将日志的最后一行减去时间戳与 $data 进行比较,我对它们进行了回显,它们完全相同,但每次仍然写入新的日志条目。我在这里错过了什么吗?如果行相同,则应该中断,如果不同,则应该写入一个新条目。
$data = "This is a test."
$date = date("m/j : g:i A: ");
$lines = file('log.txt');
$last_line = $lines[count($lines)-1];
$last_line = preg_replace('/[01][0-9]\/[0-3]?[0-9] : 1?[0-9]:[0-5][0-9] (A|P)M: /','',$last_line);
if (strcmp($data, $last_line) == 0) {
break;
} else {
file_put_contents('log.txt', $date.$data.PHP_EOL, FILE_APPEND);
}
}
I'm using the code below to compare the last line of a log minus the time stamp against $data, ive echo'd both of them and they are exactly the same however its still writing a new log entry every time. Am i missing something here? If the lines are the same it should break, if they aren't it should write a new entry.
$data = "This is a test."
$date = date("m/j : g:i A: ");
$lines = file('log.txt');
$last_line = $lines[count($lines)-1];
$last_line = preg_replace('/[01][0-9]\/[0-3]?[0-9] : 1?[0-9]:[0-5][0-9] (A|P)M: /','',$last_line);
if (strcmp($data, $last_line) == 0) {
break;
} else {
file_put_contents('log.txt', $date.$data.PHP_EOL, FILE_APPEND);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在 $last_line 上使用修剪。它后面可能有一个换行符,导致字符串不相等。
You should use a trim on the $last_line. There is probably a newline after it that is making the strings not equal.
您是否混淆了
$date
和$data
?或者这两个不同的变量?Are you mixing up
$date
and$data
? or are those two distinct variables?