【问题标题】:php text file search and delete [duplicate]php文本文件搜索和删除[重复]
【发布时间】:2013-03-14 09:50:59
【问题描述】:

我有一个文本文件 (in.txt),其中包含多行文本。我需要搜索一个变量字符串,如果找到,删除整行,但保留其他行。我使用了下面的脚本,但它似乎摆脱了所有数据并写下了我正在搜索的内容。请有人能指出我正确的方向吗? 'key' 是我要搜索的字符串。

$key = $_REQUEST['key'];
$fc=file("in.txt");


$f=fopen("in.txt","w");


foreach($fc as $line)
{
      if (!strstr($line,$key)) 
        fputs($f,$line); 
}
fclose($f);

【问题讨论】:

    标签: php search


    【解决方案1】:

    我能想到的最简单的是

    <?php
    
        $key = 'a';
        $filename = 'story.txt';
        $lines = file($filename); // reads a file into a array with the lines
        $output = '';
    
        foreach ($lines as $line) {
            if (!strstr($line, $key)) {
                $output .= $line;
            } 
        }
    
        // replace the contents of the file with the output
        file_put_contents($filename, $output);
    

    【讨论】:

      【解决方案2】:

      您已以write 模式打开文件。这将删除其所有数据。

      您应该创建一个新文件。将数据写入较新的。删除旧的。并重命名新的。

      OR

      read 模式打开此文件。将此文件的数据复制到变量中。以write 模式再次打开。并写入数据。

      【讨论】:

      • 好的,谢谢,但没有更简单的方法吗?我不知道该怎么做你的建议。
      • 那我什么时候删除该行?
      • 写入文件时。
      【解决方案3】:

      它为我工作

      <?php
      $key = $_REQUEST['key'];
      $contents = '';
      $fc=file("in.txt");
       foreach($fc as $line)
        {
          if (!strstr($line,$key))
          {
             $contents .= $line; 
           }  
        }
        file_put_contents('in.txt',$contents);
       ?>
      

      【讨论】:

      • 它带有 $contents 作为未定义的变量。我无法弄清楚我是如何排序的。干杯。
      • @user1592162 嘿,看看我编辑过的帖子,它应该对你有所帮助.. 运行此脚本后,签入.txt
      【解决方案4】:
      $key = $_REQUEST['key'];
      $fc=file("in.txt");
      
      
      $f=fopen("in_temp.txt","w");
      
      $temp = array();
      foreach($fc as $line)
      {
          if (substr($line,$key) === false) 
              fwrite($f, line);
      }
      fclose($f);
      unlink("in.txt");
      rename("in_temp.txt", "in.txt");
      

      【讨论】:

        猜你喜欢
        • 2015-02-06
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        • 2018-05-23
        • 2023-03-23
        • 2011-01-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多