1

I have a text file (in.txt) which has text on multiple lines. I need to search for a variable string and if found, delete that entire line, but keep the others. I have used the script below but it seems to get rid of all the data and write what I was searching for. Please can someone point me in the right direction? 'key' is the string for which I am searching.

$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);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Martyn
  • 73
  • 1
  • 3
  • 14

4 Answers4

4

The simplest I can come up with is

<?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);
Bart
  • 17,070
  • 5
  • 61
  • 80
1

You have opened the file in write mode. This will delete all its data.

You should create a new file. Write data to the newer one. Delete the older one. And Rename the newer one.

OR

Open this file in read mode. Copy data of this file to a variable. Open again in write mode. And write data.

Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
0

Its Working for me

<?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);
 ?>
alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
-1
$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");
KiloByte
  • 94
  • 3