动态修改tp配置文件
有时候我们要根据不同的情况去修改我们的配置文件,而tp框架只提供了读取配置文件的函数config();
自已写一个设置配置文件的函数
使用方法:
例修改tp5的 应用调试模式
setConfig('app/config',['app_debug'=>true]);
/** * 修改扩展配置文件 * @param string $file 文件地地址(从网站根目录开始,不要.php后辍) * @param array $data 要修改的数据,以数组键值对方式 */ function setConfig($file,$data){ if(is_array($data)){ $file = ROOT_PATH.$file.'.php'; foreach($data as $key=>$value){ $config_file = file_get_contents($file);//获取文件内容 //正则匹配到指定内容并替换 $pattern = "/\'\s*$key\s*'\s*=>\s*\'?\s*([\w-\.\/:]*)\'?/"; $replaceStr= "'$key' => '$value'"; //值为true/false处理 if($value === false){$replaceStr= "'$key' => false";} if($value === true){ $replaceStr= "'$key' => true";} //值为数字处理 if(is_numeric($value)){ $replaceStr = "'$key' =>".(int)$value; } $update_file = preg_replace($pattern, $replaceStr, $config_file);// 正则查找替换 $res = file_put_contents($file, $update_file); //写入配置文件 } } return $res; }
注意,配置文件中的对数值不能用双引号,一般动是用单引号的~~