'Overwrite a specific line in a text file with php [duplicate]

Need to find a simple solution to the following:

I have a php file that, when executed, should be able to replace a specific line of code within itself, with a different value on that line.

I came up with this so far:

$file = "file.php";
$content = file($file); 
foreach($content as $lineNumber => &$lineContent) {
    if($lineNumber == 19) {

        $lineContent .= "replacement_string";
    }
}

$allContent = implode("", $content);
file_put_contents($file, $allContent);

However, that does not replace the specific line. It adds the new string on a new line and that's it. I need that specific line ERASED and then REPLACED with the new string, on that line.

How would I continue about doing that? I'd love some pointers.



Solution 1:[1]

Your problem is the .= in the $lineContent .= "replacement_string"; line. Just use = or use the str_replace() or str_ireplace() function.

Solution 2:[2]

Since file() creates an array, make use of the index to select the line. Don't forget that array indexes start at 0!

$file = "file.php";
$content = file($file); 

$content[19] = "replacement_string\r\n";

$allContent = implode("", $content);
file_put_contents($file, $allContent);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 redelschaap
Solution 2 andreini