PHP-将txt文件中的行移到限制行数
我正在用PHP编写聊天,我想限制聊天文件中的行数:PHP-将txt文件中的行移到限制行数,php,file,Php,File,我正在用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($
<?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行
这显然不适用于我当前的代码,我不知道为什么,请帮助?我没有完全理解您尝试使用的逻辑。如果要删除文件开头的行,可以使用此选项。我在代码中添加了解释
$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));
参考文献:,和
编辑:不使用array\u 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));
注意:我没有添加用于防止浏览器刷新和多次添加相同消息的验证。这是留给你去实现的。你的代码产生了一些错误?@MarcoMura,没有,但由于某些原因它不起作用。你做了一些var dump来看看计数器是否得到了正确的值吗?@MarcoMura什么是var dump?我认为使用
file()
然后操纵数组会更好。然后您可以使用count()
和array\u shift()
或array\u slice()
。如果这是写入文本文件的唯一方式,我想您只需要array\u shift
。如果文件仅包含3行开头,则无需切片。其次,array\u slice($lines,0,3)
占用前3行,而不是最后3行。我注意到,如果我手动编辑文件到ex 10行,这将不起作用?我不会在末尾添加换行符,即使手动编辑文件并添加更多行,这也会起作用。这就是为什么我使用了array\u slice
,然后使用array\u shift
。通过更智能地使用array\u slice
,您可以避免计数
和数组移位
。bansi注意到,如果我将整个文件变为空,当我第一次调用send message时,消息将出现在第二行,它应该出现在第一行。