我很多时候用数组来定义配置文件,当有候我们需要动态的修改配置文件里的数组时,可以用到下面这个函数
例如的配置文件内容:<?php
return [
'cache' => 'false', //网站缓存
'cache_time' => '7200', //网站缓存
];
修改配置文件里的数组的值:/**
* 修改扩展配置文件
* @param string $file 文件地地址
* @param string $key 要修改的键名
* @param string $value 修改的值
*/
function changConfig($file='',$key='',$value=''){
$config_file = file_get_contents($file);//获取文件内容
//正则匹配到指定内容并替换
$pattern = "/\'\s*$key\s*'\s*=>\s*\'\s*([\w-]+)\s*\'/";
$replaceStr= "'$key' => '$value'";
$update_file = preg_replace($pattern, $replaceStr, $config_file);
$res = file_put_contents($file, $update_file);//保存
return $res != false? true: false;
}
使用方法:
changConfig('配置文件地址',‘要修改的键名’,'要修改为的键值');