Removing lines from a txt file


I have a data.txt file containing data like this

house # john
car # smith
boat # john

I need to remove from file data.txt , all rows having “# john” . I can load the file in array because it’s a very big file and I receive a memory error.
Is there any way to remove all rows having “# john” in the file , without loading the file in array ?

Thank you

You will want to use fgets, write lines you want to keep to a new file, something like the below

$oldfile = fopen('mylargefile.txt', 'r');
$newfile = fopen('mynewlargefile.txt', 'w');

while (($currentLine = fgets($oldfile)) !== false)
  if (strpos($currentLine, '# john') === false) // line did not contain # john
    fwrite($newfile, $currentLine);


excellent way , thank you.