Jump to content

how to open and add after multiple occurence of a line


hungryfrank

Recommended Posts

hi 

I am trying to add a few line of code using fopen

It works and it adds the lines but I have multiple occurrence of this line and I would like to all be amended.

$target_line='$second = (int)substr($raw_date, 17, 2);';
$lines_to_add= '$raw_datetime =  translate_from_gregorian($raw_datetime);'. PHP_EOL.
    '$year = (int)substr($raw_datetime, 0, 4);'. PHP_EOL.
    '$month = (int)substr($raw_datetime, 5, 2);'. PHP_EOL.
    '$day = (int)substr($raw_datetime, 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);

 

Link to comment
Share on other sites

I think I know what you are trying to do and that is to modify a block of code that exists in several files.  So - my suggestion is to stop and re-think your actions here.  Why not alter all those lines to one call to a function passing in a variable?  Then write a stand-alone module that contains this function and have it do the work.  This way if you need to change this once again, you would only have to worry about one existence of this code.

Edited by ginerjm
Link to comment
Share on other sites

I am trying to. modify existing file in a php script to add a module for world calendars.

I want to make these changes like this so if in the future there is an upgrade to the original script I can make these changes without remembering what happened.

there is only two filets change and either 0,1,2 occurrences of this line. it is always the same and hasn't changed in 15 years;)

Edited by hungryfrank
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.