replace_config替换配置文件内容方法
function replace_config($configfile, $config) {
    if(!is_file($configfile)){
        echo $configfile.'该文件不存在';
        exit;
    }
    if(!is_writable($configfile)){
        echo '没有写入权限!';
        exit;
    }
    if(!is_array($config)){
        echo '数据不能为空!';
        exit;
    }
    $pattern = $replacement = array();
    foreach($config as $k=>$v) {
        $pattern[$k] = "/['\"]".strtoupper($k)."['\"]\s*=>\s*([']?)[^']*([']?)\s*/is";
        $replacement[$k] = "'".strtoupper($k)."'=> \${1}".$v."\${2}";
    }
    $str = file_get_contents($configfile);
    $str = preg_replace($pattern, $replacement, $str);
    return file_put_contents($configfile, $str);
}用法:
$data = $_POST['data']; $conf_path = '/Home/Conf/config.php'; replace_config($conf_path,$data);
代码逻辑:
首先第一个参数configfile传入配置文件的路径,依次判断文件的是否存在,是否有写入权限。
再者第二个参数config为需要替换的数据,键值对应原配置文件的键值,变量值对应配置文件的值。
通过PHP内置函数strtoupper函数将字符串,也就是键值转换成大写,根据对应的值生成正则规则,为后面替换做铺垫。
通过file_get_contents函数打开配置文件,获取配置文件中的内容。
再根据函数preg_replace将之前对应的规则进行意义替换。
再根据file_put_contents函数写入配置文件,到这里替换配置文件的操作已经完全结束了。