删除 php 中的行?这可能吗?
我一直在努力为我的网站创建一个简单(非常简单)的聊天系统,因为我对 Javascripting/AJAX 的了解有限,在收集资源和许多好心人的帮助后,我能够创建我的简单聊天系统,但留下了一个问题。
这些消息以以下格式发布到名为“msg.html”的文件中: $name$message
然后使用 PHP 和 AJAX,我将使用以下命令立即从文件中检索消息 文件();函数和 PHP 的 foreach(){} 循环是代码:
<?php
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
if(count($data) > $max_lines){
// here i want the data to be deleted from oldest until i only have 20 messages left.
}
foreach($data as $line_num => $line){
echo $line_num . " . " . $line;
}
?>
我的问题是如何删除最旧的消息,以便只留下最新的 20 条消息?
I have been struggling to create a Simple ( really simple ) chat system for my website as my knowledge on Javascripting/AJAX are Limited after gather resources and help from many kind people I was able to create my simple chat system but left with one problem.
The messages are posted to a file called "msg.html" in this format :<p><span id="name">$name</span><span id="Msg">$message</span></p>
And then using PHP and AJAX I will retrieve the messages instantly from the file using the
file(); function and a foreach(){} loop withing PHP here is the code :
<?php
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
if(count($data) > $max_lines){
// here i want the data to be deleted from oldest until i only have 20 messages left.
}
foreach($data as $line_num => $line){
echo $line_num . " . " . $line;
}
?>
My Question is how can i delete the oldest messages so that i am only left with the latest 20 Messages ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您觉得这样的东西怎么样:
http://www. php.net/manual/en/function.file-put-contents.php 了解更多信息:)
How does something like this seem to you:
http://www.php.net/manual/en/function.file-put-contents.php for more info :)
我想你可以读取该文件,将其分解为一个数组,砍掉除最后 20 个字段之外的所有内容,然后将其写回文件,覆盖旧的......也许不是最好的解决方案,但如果你真的不能,你会想到一个解决方案按照 Delan 的建议使用数据库
I suppose you can read the file, explode it into an array, chop off everything but last 20 fields and write it back to file, overwriting the old one... Perhaps not the best solution but one that comes to mind if you really cant use database as Delan suggested
如果我没记错的话,这就是所谓的循环赛。
据我所知,您无法删除文件的任意部分。您需要用新内容覆盖该文件(或创建一个新文件并删除旧文件)。您还可以将消息存储在单独的文件中,但这当然意味着最多可读取
$max_lines
个文件。您还应该使用 flock() 以避免数据损坏。根据平台的不同,它不是 100% 可靠,但总比没有好。
That's called round-robin if I recall correctly.
As far as I know, you can't remove arbitrary portions of a file. You need to overwrite the file with the new contents (or create a new file and remove the old one). You could also store messages in individual files but of course that implies up to
$max_lines
files to read.You should also use flock() to avoid data corruption. Depending on the platform it's not 100% reliable but it's better than nothing.