-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
  • 410
  • 1
  • 6
  • 16

1 Answers1

4

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
  • 14,286
  • 11
  • 68
  • 157