2

I would like to know how can I add text at the begining of a specific line in a txt file using PHP.

For example line 2 and 4:

Line 1
Line 2
Line 3
Line 4

to

Line 1
Whatever Line 2
Line 3
Whatever Line 4

Edit: The content of each line is variable all time, so I can't use replace or search for a specific word.

Thank you :)

user3019668
  • 75
  • 1
  • 5
  • One method might be to split into an array, and modify elements of the array. – Regular Jo Dec 07 '14 at 20:22
  • possible duplicate of [how to replace a particular line in a text file using php?](http://stackoverflow.com/questions/3004041/how-to-replace-a-particular-line-in-a-text-file-using-php) – Regular Jo Dec 07 '14 at 20:24
  • I can't use replace because the content of the file is variable. – user3019668 Dec 07 '14 at 20:33
  • Well then, my first suggestion should work, this answer should help you, using explode(): http://stackoverflow.com/questions/1483497/how-to-put-string-in-array-split-by-new-line – Regular Jo Dec 07 '14 at 20:36

2 Answers2

3

Get the contents of the file, with each line as an index of the returned array, using file():

$lines = file('path/to/your/file');

Then you can do whatever you need by using the correct line index:

// prepend content to line 2:
$abc = 'abc' . $lines[1];
// append content to line 4:
$xyz = $lines[3] . 'xyz';

The whole process (get the contents, update them, and then replace the original file):

$file = 'yourfile.txt';
$lines = file($file);
$lines[1] = 'xxx' . $lines[1]; // prepend content to line 2.
$lines[3] = 'yyy' . $lines[3]; // prepend content to line 4.
file_put_contents($file, implode('', $lines));"
timclutton
  • 12,682
  • 3
  • 33
  • 43
0

If you want to add every second line use this code

$n = 0;
for ($i = 1; $i <= 10; $i++) {
    if($n % 2 == 1) {
     echo "Whatever Line: ".$i."<br>";
    } else {
    echo "Line ".$i."<br>";
    } $n++;
}

but if you want add only second and 4th line use this code.

 for ($i = 1; $i <= 10; $i++) {
            if(($i == 2) or ( $i == 4)){
             echo "Whatever Line: ".$i."<br>";
            } else {
            echo "Line ".$i."<br>";
            }
    }
  • The content of the lines are variable, it's not the same all time. I just want to add text at the begining of the line number 2 and 4. Each line has different text, it's not "Line X, Line X...". – user3019668 Dec 07 '14 at 20:32
  • I just want to add text at the begining of the line number 2 and 4 (I know the line but I don't know what's the content).. I think I didn't explaint it well.. sorry :/ – user3019668 Dec 07 '14 at 20:43
  • realy i didnt understand. can you explain? – Ismail Altunören Dec 07 '14 at 20:58
  • I want to edit the lines number 2 and number 4 but without using the content, only the number of the line. I want to add text at the begining of the line number 2 and number 4. – user3019668 Dec 07 '14 at 21:05