2011-09-01 63 views
0

我有一個簡單的ini文件:PHP的字符串比較錯誤解析ini文件

[section_one] 
test = abc 

[section_two] 
yada = blah 
#and_so=on 

我寫了一個解析器函數來更新其B/C我的評論char是不是「#」「;」 - 所以parse_ini_file()抱怨。但這裏是我的快速&骯髒的解決方案:

<?php 
function edit_ini_file ($fName, $fKey, $fVal) { 
    print"<h4>Search: $fKey = $fVal </h4>"; 
    // declarations 
    $_comntChar='#'; 
    $_headrChar='['; 
    $keyMatch=FALSE; 
    $iniArray = array(); // new array in memory 
    $dataOut = ''; // datastream for output file 
    // temp cursor vars for looping & reporting 
    $verbose = 1; 
    $curSec = ''; // current section 
    $curKey = ''; // current key 
    $curVal = ''; // current value 
    $curLine=-1; // current line Number 
    if (isset($fName)) { 
    if (!is_file($fName)) return FALSE; 
    $lines = file($fName); 
    //read file as array of lines 
    foreach ($lines as $line) { 
     $curLine+=1; 
     if ($verbose) print '<br/>['.$curLine.'][IN:] '.$line; 
     //parse for k/v pairs, comments & section headings 
     if ( (strpos($line,$_headrChar)==1) // assume heading 
      || (strpos($line,$_comntChar)==1) // assume comment 
      || (!strpos($line,'=')) // also skip invalid k/v pairs 
     ){ 
      array_push($iniArray, $lines[$curLine]); //stuff the entire line into array. 
      if ($verbose) print " - no k/v"; 
     } else { // assume valid k/v pair 
     //split k/v pairs & parse for match 
     $pair = explode('=', $line); 
     $curKey = trim($pair[0]); 
     $curVal = trim($pair[1]); 
     if ($verbose) print "[KV]: k=$curKey:v=$curVal"; 
     if (trim($curKey) === trim($fkey)) { // <=== THE BUGGER: never returns true: 
      $keyMatch=TRUE; 
      print ("MATCH: Replacing value in for key=$curKey in Section $curSec at line $curLine<br/>"); 
      array_push ($iniArray, array($curKey => $fVal)); 
     } else { 
     array_push ($iniArray, array($curKey => $curVal));  
     } //end-matcher 
     } //end-parser 
    } //end foreach 
    if (!$keyMatch) { //append new data to end 
     print "<br/>Key not Found. Appending! <br/>"; 
     array_push ($iniArray, array($fKey => $fVal)); 
    } 
    //reformat nested array as one long string for a single bulk-write to disk. 
    foreach($iniArray as $curSect => $val) { 
    if (is_array($val)) { 
     foreach($val as $curKey => $curVal) 
      $dataOut .= "$curKey = $curVal\n"; 
    } else { $dataOut .= "$val"; } 
    } 
    print "dataout:<pre>" .$dataOut. "</pre>"; 
    //put file & pass return val 
    return (file_put_contents($filename, $dataOut)) ? TRUE : FALSE;  
}//if isset 
}//end-func 

基本上我只是爆炸的一個文本文件中的行由行餡一個新的數組,併爲之傾倒回磁盤

MY BUG:由於某種原因我比較努力的strcmp()或「==」或「===」似乎永遠不會工作...

if (trim($curKey) === trim($fkey)) { doSomething.. } 

那個小雞姦是我發瘋b/C我知道它得是一些愚蠢的事。

在正確的方向上的任何一點,將不勝感激......

+1

你知道['parse_ini_file()'](http://php.net/manual/en/function.parse-ini-file.php),對不對? – Phil

回答

1

它是$ FKEY或$ FKEY?

做出決定!

;)

+0

所以...是這樣嗎? –