[英]How to execute something like sed -i '/^MAIL_DRIVER=/s/=.*/=log/' .env using PHP to update variable value in laravel dotenv file
In Laravel sometime I uptade environment values with sed with: 在Laravel有时我用sed来获取环境值:
sed -i '/^MAIL_DRIVER=/s/=.*/=log/' .env
Can anyone propose and alternative to do this with PHP? 任何人都可以建议和替代使用PHP吗?
UPDATE: I used Laravel/dotenv .env file as a example to give some context to the question but I'm not interested in how to change enviroment variables programatically my interest is how to perform sed "like" operations with php file manipulation function or if exists some library to do that. 更新:我使用Laravel / dotenv .env文件作为示例给出问题的一些上下文,但我对如何以编程方式更改环境变量不感兴趣我的兴趣是如何使用php文件操作函数执行sed“like”操作或如果存在一些库来做那件事。 I also know i could use system o passthru functions, that's what I'm already doing I just curios about how to manipulate files in this way using PHP 我也知道我可以使用system o passthru函数,这就是我已经在做的事情我只是好奇如何使用PHP以这种方式操作文件
While Laravel uses the dotenv library to read, it offers no way to programatically update the .env
file. 虽然Laravel使用dotenv库进行读取,但它无法以编程方式更新.env
文件。 You can however update the configuration value using preg_replace
. 但是,您可以使用preg_replace
更新配置值。 Here's a one line solution: 这是一个单行解决方案:
file_put_contents(base_path('.env'), preg_replace("/(MAIL_DRIVER)=(.*)/", "$1=log", file_get_contents(base_path('.env'))));
Here's also the solution expanded into multiple lines and explained: 这里也是解决方案扩展到多行并解释:
// Read the .env file contents
$env = file_get_contents(base_path('.env'));
// Replace the value using regex matching
$env = preg_replace("/(MAIL_DRIVER)=(.*)/", "$1=log", $env);
// Write the updated contents to the file
file_put_contents(base_path('.env'), $env);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.