【发布时间】: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