Search code examples
phpreplaceline

Php replace line in a file txt


<?php
$myFile = "/home/user1/www/cgi-bin/mytext.txt";
$lines = file($myFile);
$lines[3] = $_POST['title'];
file_put_contents($myFile , implode("\n", $lines));
?>

I would change only the row "number 3" without changing the other rows, where mistake?

i have input mytext.txt:

  • line1 -------------------------------------
  • line2 #WORD:
  • line3 CHANGETHIS
  • line4
  • line5 HELLO
  • line6 PIPPO
  • line7 FOO
  • line8 KATEEOWEN

after lunch script this is the ouput mytext.txt:

  • line1 -------------------------------------
  • line2
  • line3 #WORD:
  • line4
  • line5 CHANGETHIS
  • line6
  • line7 $_POST['title']
  • line8 HELLO
  • line9
  • line10 PIPPO
  • line11
  • line12 FOO
  • line13
  • line14 KATEEOWEN

Solution

  • You can either use the FILE_IGNORE_NEW_LINES constant in file() or don't use more newlines:

    file_put_contents($myFile , implode('', $lines));
    

    Or just this as it will be imploded for you:

    file_put_contents($myFile , $lines);
    

    But you'll need to add a newline here:

    $lines[3] = $_POST['title'] . "\n";
    

    So this might be the most straight forward:

    $lines = file($myFile, FILE_IGNORE_NEW_LINES);
    $lines[3] = $_POST['title'];
    file_put_contents($myFile , implode("\n", $lines));