I have been confused about this question for a long time. I hope someone can give me some advice.
If the content in config.php is:
'111111', 'k2' => '222222', 'k3' => '333333', );
or it could be:
{ "k1": "111111", "k2": "222222", "k3": "333333", }
How should I modify the value under 'k1'? How can I achieve this without using str_replace? (Because the value of 'k1' is not fixed, the method I want is to find the key, then modify the value of the key and save the file)
The first one is easier to do, but the second one should be checked first to see if it is written correctly. This structure is similar to a JSON object but not, so it is not easy to do.
The first method
Mainly use
var_export
to output an array that can be read by PHP. When the second parameter of this function isfalse
, it will be output directly. When it istrue
, the result will be returned to the variable.One thing that needs to be reminded is that the array layout generated by this function is not very good-looking. If you mind, just write one yourself.
Update
Modify the example code of
k1
In fact, the easiest way is not to write the config file like this. The config file format is generally as follows:
External files can directly assign the value of the array to a variable by requiring the file, such as
It’s easy to get and change values, and it’s also easy to write back to files.