编辑配置文件的PHP函数

标签 php function key-value keyvaluepair

我正在寻找可用于编辑文本文件中的键/值对的 PHP 函数。

我想做什么(PHP):

changeValue(key, bar);

并在 setings.txt 中:

key = foo
key2 =foo2

更改为:

key = bar
key2 = foo2

到目前为止我得到了什么(不工作):

function changeValue($input) {
    $file = file_get_contents('/path/to/settings.txt');
    preg_match('/\b$input[0]\b/', $file, $matches);
    $file = str_replace($matches[1], $input, $file);
    file_put_contents('/path/to/settings.txt', $file);
}

How to update an ini file with php?让我开始。我阅读了许多其他问题,但我无法让它发挥作用。

最佳答案

我会使用至少带有 JSON_PRETTY_PRINT 选项的 JSON 来写入和 json_decode() 来读取。

// read file into an array of key => foo
$settings = json_decode(file_get_contents('/path/to/settings.txt'), true);

// write array to file as JSON
file_put_contents('/path/to/settings.txt', json_encode($settings, JSON_PRETTY_PRINT));

这将创建一个文件,例如:

{
    "key": "foo",
    "key2": "bar",
    "key3": 1
}

另一种可能性是 var_export() 使用类似的方法,或者另一个简单的例子来说明您的要求:

// read file into an array of key => foo
$string = implode('&', file('/path/to/settings.txt', FILE_IGNORE_NEW_LINES));
parse_str($string, $settings);

// write array to file as key=foo
$data = implode("\n", $settings);
file_put_contents('/path/to/settings.txt', $data);

所以读入文件,改变设置$setting['key'] = 'bar';然后写出来。

关于编辑配置文件的PHP函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34665423/

相关文章:

Swift 相当于字符串文字接口(interface)吗? - `request(method: ' 帖子'|'put')`

javascript - 我有两个功能,但最后一个会触发

powershell - 使用powershell从xml读取键值

JavaScript:单独声明和定义函数?

mongodb - 没有文件系统的键值存储?

javascript - 如何将用户输入存储为 typescript 中的对象键?

php - 如何在帖子中上传数百张图片?

php - Activerecord 关联 : create new object (find class)

php header 方法不重定向

php - php 的 mySql INTO OUTFILE 问题