Search code examples
phpstringlinestrpos

Replacing a line in a file with PHP


I am currently trying to replace a line in a configuration file to update a version. The line looks like requiredBuild = 123456; and I need to change the numbering. I have got the following which inserts the new line after it, but I need to actually replace the existing line instead.

How would this be accomplished? ftell() is giving me the POS after the line I want to replace but removing the original line is where I am confused. Is there some way to just do like the ftell() - strlen(thisline) and replace it with ''?

<?

    $config = 'serverDZ.cfg';

    $file=fopen($config,"r+") or exit("Unable to open file!");
    $insertPos=0;

    while (!feof($file))
    {
        $line=fgets($file);

        if (strpos($line, 'requiredBuild') !== false)
        {
            $insertPos = ftell($file);
            $newline =  "requiredBuild = 124971;\n";

            break;
        }
    }

    fseek($file, $insertPos);
    fwrite($file, $newline);

    fclose($file);

?>

Solution

  • Try this solution:

    <?php
    $content = file($path);
    
    foreach ($content as $line_num => $line) {
        if (false === (strpos($line, 'requiredBuild'))) continue;
    
        $content[$line_num] = "requiredBuild = 124971;\n";
    }
    
    file_put_contents($path, implode($content));