我正在用PHP编写聊天,我想限制聊天文件中的行数:
<?php
$filename = "chat.txt";
file_put_contents($filename, file_get_contents($filename) . $_POST["message"] . "\r\n");
$max_lines = 3;
$lines = 0;
$handle = fopen($filename, "r");
while (!feof($handle)) {
$line = fgets($handle);
$lines++;
}
fclose($handle);
$lines_over = $lines - $max_lines;
if ($lines_over > 0) {
while ($lines_over > 0) {
file_put_contents($filename, implode("\r\n", file($filename, FILE_IGNORE_NEW_LINES)));
$lines_over--;
}
}
?>
,我想在开头删除尽可能多的行,使文件只有3行。
显然这与我目前的代码无关,我不知道为什么,请帮忙吗?
答案 0 :(得分:0)
我没有完全理解你正在尝试使用的逻辑。如果要删除文件开头的行,可以使用它。我在代码中添加了解释。
$filename = "chat.txt";
$max_lines = 3;
//Read lines into an array
$lines = file($filename);
//trim your array to max_lines
$lines = array_slice($lines, -1 * $max_lines);
//check if we have max_lines
if (count($lines) == $max_lines){
//remove one from the beginning
array_shift($lines);
}
//add your new line
$lines[] = trim($_POST["message"]) . "\r\n";
file_put_contents($filename, implode($lines));
参考文献:file,array_shift和array_slice
编辑:不使用array_shift
$filename = "chat.txt";
$max_lines = 3;
//Read lines into an array
$lines = file($filename);
//trim your array to just one less item than max lines
$lines = array_slice($lines, -1*($max_lines-1));
//confirm newline is available in the last line
$lines[count($lines)-1] = trim($lines[count($lines)-1]) . "\r\n";
//add your new line with newline
$lines[] = trim($_POST["message"]) . "\r\n";
file_put_contents($filename, implode($lines));
Edit2:解决了尚未创建空文件和文件的问题。
$filename = "chat.txt";
$max_lines = 3;
//Read lines into an array only if file_exists
//On first run this file may not be there
if(file_exists($filename)){
$lines = file($filename);
}
//trim your array to just one less item than max lines
//This is needed only if there are lines
if (!empty($lines)){
$lines = array_slice($lines, -1*($max_lines-1));
//confirm newline is available in the last line
$lines[count($lines)-1] = trim($lines[count($lines)-1]) . "\r\n";
}
//add your new line with newline
$lines[] = trim($_POST["message"]) . "\r\n";
file_put_contents($filename, implode($lines));
注意:我没有添加用于防止浏览器刷新和多次添加相同消息的验证。这留给你实现。