php - What's the best way to change a key value in an .ini file? -


i have task accomplish, , i've been trying regex hours no avail. little , teaching appreciated. .ini file format is:

es=spanish en=english token=token files=files 

the goal of routine

  1. get key needs changed,
  2. figure out current value of key is,
  3. add comments old value , changed it,
  4. change value.

so, example, if want change value belonging en english eigo, end with:

es=spanish #changed 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 old value     $matches = array();     preg_match('~'.$key.'\s?=[^\n$]+~iu',$content,$matches);      $commentlines = '# change ' . $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 working fine, until realized if changed key short string, en, regex matches en in token, , changes that, messes whole file:

tok#changed .... 

so, few questions:

  1. because each key should unique, should using regex this? there faster/cleaner/better method should using?

  2. why when add ^ regex on line preg_replace doesn't match beginning of line , rid of token matching problem?

    preg_replace('~^'.$key.'\s?=[^\n$]+~iu',$newentry,$content) 

the information give bit vague. being stored in file? if so, seems want version control software subversion. keep track of state of code/ini files @ point in time, made change, , if people want put in message doing, handle well.

your regex seems bit overcomplicated. , multiline search , replace, need use m modifier.

try:

$key = 'en'; preg_replace('~^'.$key.'=.*$~m', $newentry, $content); 

tested @ 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 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -