我正在寻找可用于编辑文本文件中的键/值对的 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/