What's the best way to change a key value in an .ini file?
I have a task to accomplish, and I've been trying with regex for hours to no avail. A little help and some teaching would be appreciated. The .ini file format is:
ES=Spanish
EN=English
TOKEN=Token
FILES=Files
The goal of my routine is to
- Get a key that needs to be changed,
- Figure out what the current value of that key is,
- add some comments about the old value and who changed it,
- change the value.
So, for example, if I want to change the value belonging to EN from English to Eigo, I would end up with:
ES=Spanish
#Changed by Jane Doe on <date>
#Old value: EN=English
EN=Eigo
TOKEN=Token
FILES=Files
My code:
$content = "EN=English\n"
. "ES=Spanish\n"
. "TOKEN=Token\n"
. "FILES=Files\n";
$key = 'EN';
$newValue = 'Eigo";
$editor = 'Jane Doe';
//get the old value
$matche开发者_运维技巧s = array();
preg_match('~'.$key.'\s?=[^\n$]+~iu',$content,$matches);
$commentLines = '# Change by ' . $editor . ' on ' . date("m/d/Y g:i a") . "\n";
$commentLines .= '# Old value: ' . $matches[0] . "\n";
$newValueLine = $key.'='.$newValue. "\n";
$newEntry = $commentLines . $newValueLine;
$content = preg_replace('~'.$key.'\s?=[^\n$]+~iu',$newEntry,$content);
This was working fine, until I realized that if someone changed the key for a short string, like EN, then my regex matches the EN in TOKEN, and also changes that, but messes up the whole file:
TOK#Changed by ....
So, a few questions:
Because each KEY should be unique, should I even be using regex for this? Is there a faster/cleaner/better method I should be using?
Why when I add a
^
to the regex on the line withpreg_replace
doesn't this match the beginning of the line and get rid of my TOKEN matching problem?preg_replace('~^'.$key.'\s?=[^\n$]+~iu',$newEntry,$content)
The information you give is a bit vague. Is this being stored in a file? If so, it seems like what you really want is version control software like subversion. It will keep track of what the state of the code/ini files were like at any point in time, who made a change, and if people want to put in a message about what they were doing, it will handle that as well.
Your regex seems a bit overcomplicated. And for multiline search and replace, you need to use the m modifier.
Try:
$key = 'EN';
preg_replace('~^'.$key.'=.*$~m', $newEntry, $content);
Tested at http://www.spaweditor.com/scripts/regex/index.php with:
Regex:
/^EN=.*$/m
Data:
EN=English
ES=Spanish
TOKEN=Token
FILES=Files
Replace:
FOO=bar
Function:
preg_replace
Result:
FOO=bar
ES=Spanish
TOKEN=Token
FILES=Files
精彩评论