Search code examples
phpfopenfwrite

using fopen to add some text after multiple appearance of a text


what I am trying to do is to create an installer for my world calendar in a script. I need to make some changes to one of the files in. the main script. I have managed to use the code above to make the change that I want. the problem is that there is more than one occurrence. how do I make the same change every time that the string is repeated. it could happened 0 or 1 or 2 times

$target_line='$second = (int)substr($raw_date, 17, 2);';
$lines_to_add= '$raw_date =  translate_from_gregorian($raw_date);'. PHP_EOL.
    '$year = (int)substr($raw_date, 0, 4);'. PHP_EOL.
    '$month = (int)substr($raw_date, 5, 2);'. PHP_EOL.
    '$day = (int)substr($raw_date, 8, 2);'. PHP_EOL;
$config ='includes/functions/general.php';
$file=fopen($config,"r+") or exit("Unable to open file!");
$insertPos=0;  // variable for saving //Users position
 while (!feof($file)) {
    $line=fgets($file);
    if (strpos($line,$target_line)!==false) { 
        $insertPos=ftell($file);    // ftell will tell the position where the pointer moved, here is the new line after //Users.
        $newline =  $lines_to_add;
    } else {
        $newline.=$line;   // append existing data with new data of user
    }
}

fseek($file,$insertPos);   // move pointer to the file position where we saved above 
fwrite($file, $newline);

fclose($file);


Solution

  • Read the entire file into a variable. Use str_replace() to make all the replacements. Then write the result back to the file.

    $contents = file_get_contents($config);
    $contents = str_replace($target_line, $target_line . PHP_EOL . $lines_to_add, $contents);
    file_put_contents($config, $contents);