gus
gus

Reputation: 1798

Edit file line by line

I'm making a program that reads a file line by line and deletes the lines that say Hand #[any numbers]

$file_name = 'the_file.txt';
$file_handle = fopen($file_name,"r+");

while(! feof($file_handle)) {
    $file = fgets($file_handle);

    if (preg_match("/^(Hand\s#\d+)/m", $file)) {
        fwrite($file_handle, preg_replace("/^(Hand\s#\d+)/m", "", $file));
    }
    
  }

fclose($file_handle);

This code does nothing however if put echo $file . '<br />'; It prints every line with Hand #[any numbers] So think its a problem with fwrite($file_handle, preg_replace("/^(Hand\s#\d+)/m", "", $file)); Which work fine if the file is not read line by line.

Upvotes: 0

Views: 1275

Answers (3)

bloodstix
bloodstix

Reputation: 142

You want to exclude all lines that start with "Hands #number" ? Then why do you use preg_match to find the lines, to write them replaced by nothing to the file? Just exclude them and keep the lines you want in an array. Or open a secondary file and write each line directly to the new file, if memory limits are an issue.

$filename = "the_file.txt";
$handle = fopen($filename, "r+") or die("Could not open $filename" . PHP_EOL);

$keep = array();
while(!feof($handle)) {
    $line = fgets($handle);
    if(!preg_match("/^(Hand\s#\d+)/m", $line)) {
        $keep[] = $line;
    }
}
rewind($handle);
fwrite($handle, implode(PHP_EOL, $keep));
fclose($handle);

Upvotes: 0

Catherine Tsokur
Catherine Tsokur

Reputation: 236

It can be related to the file pointer position and also to the fact that you are writing to the file, and not deleting anything. See function http://us.php.net/manual/en/function.fseek.php

So you are not deleting a line but writing a new line in the place after the line you have just read (which is left in place). In this case it's better to write in different file.

Upvotes: 0

sa289
sa289

Reputation: 700

Try writing to a different file than you are reading from. It's possible that PHP doesn't like you trying to overwrite parts of the file as you're reading from it.

Also double-check that the PHP script has permission to write to the file. Try something simple like make a backup of it and then do file_put_contents($file_name, 'test');

Upvotes: 1

Related Questions