Home > other >  Find specific word and replace the whole line
Find specific word and replace the whole line

Time:05-28

i want to find specific word and replace the whole line. for example lets say i have file that have this text

some random
text that is meaningless
and i want to
replace this line here // im looking for here to replace.
blah blah blah

i want to find 'line here' word in the text that i have. and replace the whole line with 'this is replaced line' so my text will be like this :

some random
text that is meaningless
and i want to
this is replaced line // new repalced line
blah blah blah

i searched on the net about this and i could only find replacing specific word and not the whole line.

CodePudding user response:

I think you need to do 4 operations in your algorithm:

  1. split your string into an array of lines;
  2. walk this array using foreach
  3. try to find needed word using strpos
  4. if it does not exist add to $result[] = $val, otherwise $result[] = 'new repalced line'
  5. use implode to concatenate strings

CodePudding user response:

You can read the file line-by-line using fgets while keeping track of the start position of each line with ftell.

Then check for the existence of the string and, if found, fseek back to the start of the line and overwrite it.

<?php
  $stream = fopen("input.txt", "r ");
  
  if ($stream) {
    while (!feof($stream)) {
      $position = ftell($stream);
      $line = fgets($stream);
      if (strpos($line, "line here") !== false) {
        fseek($stream, $position);
        fwrite($stream, "this is replaced line");
      }
    }
    fclose($stream);
  }
?>
  •  Tags:  
  • php
  • Related