【问题标题】:php replace an string on exist file .envphp替换现有文件.env上的字符串
【发布时间】:2021-10-11 00:16:15
【问题描述】:

我的问题类似这样:Replace string in text file using PHP

但我想用规范变量替换 例如,我已经存在文件.env

variable_1=data_2021
variable_99=data_2050
variable_991=data_2061

那么我如何用指定名称变量替换值? 我想用data_2051 替换data_2050 而不更改变量为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);

上面的代码只是删除所有内容文件.env并重新添加variable_99=value

【问题讨论】:

  • 使用file(),它将文件转换为数组,然后遍历它并替换,然后执行fwrite()file_put_contents()

标签: php


【解决方案1】:

你可以像下面这样使用file_put_contentsparse_ini_file

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));
}

然后你可以这样调用,你可以用array key, value替换多个.env变量。 keyold valuevaluenew value

modifyEnv('../../.env.securepay',[
    'variable_99' => 'data_2051',
    'variable_1' => 'data_2051'
]);

【讨论】:

  • ``` 'variable_99' => 'variable_99=data_2051' ``` 但是我的条件我不知道我的值,所以当我尝试代码时输出是variable_1=data_2021 variable_99=data_2051=data_2050
  • 代码仍然替换所有字符串,我的问题是without change on other text ,所以我只想更改一些变量,例如 variable_99。其他变量是常量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2012-04-27
相关资源
最近更新 更多