search

Home  >  Q&A  >  body text

Replace an entire line in a text file when a specific word is encountered

How to replace specific lines of text in a file using php?

I don't know the line number. I want to replace lines containing specific words.

P粉883278265P粉883278265422 days ago472

reply all(2)I'll reply

  • P粉138711794

    P粉1387117942023-10-19 13:40:07

    You must overwrite the entire file.

    So, for a relatively small file, read the file into an array , search for the word, replace the found lines, all the rest is written to the file .

    For large files, the algorithm is slightly different, but generally the same.

    The important part isFile locking

    This is why we prefer databases.

    reply
    0
  • P粉155710425

    P粉1557104252023-10-19 13:24:24

    A method that can be used for smaller files that fit in your memory twice:

    $data = file('myfile'); // reads an array of lines
    function replace_a_line($data) {
       if (stristr($data, 'certain word')) {
         return "replacement line!\n";
       }
       return $data;
    }
    $data = array_map('replace_a_line', $data);
    file_put_contents('myfile', $data);

    Quick note, PHP > 5.3.0 supports lambda functions, so you can remove the named function declaration and shorten the mapping to:

    $data = array_map(function($data) {
      return stristr($data,'certain word') ? "replacement line\n" : $data;
    }, $data);

    Theoretically you could make this a single (harder to follow) php statement:

    file_put_contents('myfile', implode('', 
      array_map(function($data) {
        return stristr($data,'certain word') ? "replacement line\n" : $data;
      }, file('myfile'))
    ));

    For larger files another (less memory intensive) method should be used:

    $reading = fopen('myfile', 'r');
    $writing = fopen('myfile.tmp', 'w');
    
    $replaced = false;
    
    while (!feof($reading)) {
      $line = fgets($reading);
      if (stristr($line,'certain word')) {
        $line = "replacement line!\n";
        $replaced = true;
      }
      fputs($writing, $line);
    }
    fclose($reading); fclose($writing);
    // might as well not overwrite the file if we didn't replace anything
    if ($replaced) 
    {
      rename('myfile.tmp', 'myfile');
    } else {
      unlink('myfile.tmp');
    }

    reply
    0
  • Cancelreply