简体   繁体   English

替换或删除txt文件中的行

[英]replace or delete line in txt file

comm.php comm.php

<?
$com = $req_user_info['comments'];
$name = $username;

if($_POST) {
$postdate = date("d M y h:i A");
$content = $_POST['commentContent'];
$handle = fopen("$com","a");
fwrite($handle,"<b>" . $name . "</b>:<br>" . $content . "<br>" . $postdate . "<br>"); 
fclose($handle);}
?>

<html>
<body>
<form action = "" method = "POST">
Post a Comment<br><textarea rows="10" cols="30" name="commentContent"></textarea><br>
<input type="submit" value="Comment"><p>
Comments<p>
<? 
include($com);
?>
</body></html>

/*$req_user_info['comments']; = data.txt*/

data.txt data.txt

Alex: sometext 20 Feb 12 11:11 AM
Alex: sometext 20 Feb 12 11:38 AM

What I want to do is delete (or replace with nothing) name, content and postdate. 我想做的是删除(或不添加任何内容)名称,内容和发布日期。

Example: 例:

Alex: sometext 20 Feb 12 11:11 AM Delete Alex:sometext 20 Feb 12 11:11 AM删除

Alex: sometext 20 Feb 12 11:38 AM Delete Alex:sometext 20 Feb 12 11:38 AM删除

So after I click delete and refresh the page I want the line to be gone. 因此,在单击删除并刷新页面后,我希望该行消失。

Instead of just including the file normally, you could use fgets to read line by line ( http://www.php.net/manual/en/function.fgets.php ). 您可以使用fgets逐行读取( http://www.php.net/manual/en/function.fgets.php ),而不仅仅是正常地包含文件。 Store each line number as you iterate though, then on your delete link, pass the line number. 不过,请在迭代时存储每个行号,然后在删除链接上传递该行号。

<a href="page.php?delete=XXX">Delete</a>

When you then want to delete, simple go through each line and rewrite the file, skipping the line that was given with the delete link variable $_GET['delete']. 然后,当您要删除时,只需遍历每一行并重写文件,就可以跳过删除链接变量$ _GET ['delete']给出的行。 Just make sure you're counting as you write each new line so you know when to skip a line. 只需确保在编写每一行时都在计数,就可以知道何时跳过一行。

Using the PHP example: 使用PHP示例:

<?php
    $counter = 0;
    $handle = @fopen("/tmp/inputfile.txt", "r");
    if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $counter++;
        echo $buffer . '<a href="page.php?delete='.$counter.'">delete</a>';
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM