How to modify the content of a specific line in a file …

To edit the content of a specific line in a file, you can follow these steps:

  1. Open the file and read all lines into an array.
$filename = 'path/to/file.txt';
$lines = file($filename);
  1. Find the line number that needs to be modified, and make changes to the content of that line.
$lineNumber = 3; // 需要修改的行数
$newContent = 'new content'; // 新的内容
$lines[$lineNumber - 1] = $newContent . "\n"; // 修改数组中对应行的内容
  1. Write the modified content back to the file.
file_put_contents($filename, implode('', $lines));

Note: Line numbers start counting from 1, so subtract 1 from the lines that need to be modified to obtain the corresponding row index in the array. Also, add a line break after the modified content before writing it into the array to preserve the format of the file.

The complete sample code is as follows:

$filename = 'path/to/file.txt';
$lines = file($filename);

$lineNumber = 3; // 需要修改的行数
$newContent = 'new content'; // 新的内容
$lines[$lineNumber - 1] = $newContent . "\n"; // 修改数组中对应行的内容

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

Please replace path/to/file.txt with the actual path of the file to be modified, 3 is the line number to be modified, and new content is the new content.

bannerAds