Are there any best practices for manually editing specific lines in a file with PHP?

When manually editing specific lines in a file with PHP, it is important to first read the contents of the file, make the necessary changes to the specific lines, and then write the updated contents back to the file. This can be achieved by using functions like file_get_contents(), explode(), implode(), and file_put_contents().

$file = 'example.txt';
$lines = file($file); // Read the file into an array
$lineNumber = 3; // Line number to edit
$newLine = 'New content for line 3';

if(isset($lines[$lineNumber-1])) {
    $lines[$lineNumber-1] = $newLine . PHP_EOL; // Update the specific line
    $newContent = implode('', $lines); // Convert array back to string
    file_put_contents($file, $newContent); // Write the updated content back to the file
} else {
    echo 'Line number does not exist in the file.';
}