0

my question is similiar like this : Replace string in text file using PHP

but i want replace by spesification variable for example, i have already file exist .env

variable_1=data_2021
variable_99=data_2050
variable_991=data_2061

so how i can replace by spesificiation name variable for the value ? i want replace data_2050 with data_2051 without change on other text where the variable is variable_99

        $myfile = fopen("../../.env.securepay", "w") or die("Unable to open file!");
        fwrite($myfile, 'variable_99='.$value);
        fclose($myfile);

        // $myfile = fopen("../../.env", "w") or die("Unable to open file!");
        // fseek($myfile, 0);
        // fwrite($myfile, 'variable_99 ='.$value);
        // fclose($myfile);

        // $oldMessage = 'variable_99';
        // $deletedFormat = '';

        // //read the entire string
        // $str=file_get_contents('../../.env.securepay');

        // //replace something in the file string - this is a VERY simple example
        // $str=str_replace($oldMessage, $deletedFormat, $str);

        // //write the entire string
        // file_put_contents('../../.env', $str);

above code just remove all the content file .env and re added variable_99=value

1
  • use file(), it will conver file to array, then iterate over it and replace and then do fwrite() or file_put_contents() Commented Aug 6, 2021 at 3:52

1 Answer 1

0

You can use file_put_contents and parse_ini_file like this follow below

function modifyEnv($path,$values = []) {
    $env = [];
    foreach(parse_ini_file($path) as $k => $value) {
        if(in_array($k,array_keys($values))) {
            $env[$k] = "$k={$values[$k]}";
        }
    }
    return file_put_contents($path,implode(PHP_EOL,$env));
}

Then you can call like this, you can replace multiple .env variables by using array key, value. key is the old value and the value is the new value

modifyEnv('../../.env.securepay',[
    'variable_99' => 'data_2051',
    'variable_1' => 'data_2051'
]);
Sign up to request clarification or add additional context in comments.

2 Comments

``` 'variable_99' => 'variable_99=data_2051' ``` but my conditions i dont know my value, so when i try the code the output is variable_1=data_2021 variable_99=data_2051=data_2050
the code still replace all string , my question is without change on other text so i only want to change some variable only, for example is variable_99. other variable is constanta.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.