-2

I have a text file names data.dat containing space separated strings on each line. I want to delete a whole line starting with a specific from it, Please provide tested php code for it. I'm using php 5.4+

File Contents :

abc samle sample
this abc sample
xyz test sample sample

For example, I have $str="this". So in this case I want to delete 2nd line, For general that could occur at first line or middle or end. Main thing is I dont want any empty line. So new file should be

abc samle sample
xyz test sample sample
Jamshad Ahmad
  • 391
  • 1
  • 5
  • 16

1 Answers1

3

Try with this:

<?php
    $f = "data.dat";

    $term = "this";

    $arr = file($f);

    foreach ($arr as $key=> $line) {

        //removing the line
        if(stristr($line,$term)!== false){unset($arr[$key]);break;}
    }

    //reindexing array
    $arr = array_values($arr);

    //writing to file
    file_put_contents($f, implode($arr));
?>
Whirlwind
  • 13,561
  • 7
  • 57
  • 141