【发布时间】:2011-09-01 02:20:29
【问题描述】:
我有一个简单的ini文件:
[section_one]
test = abc
[section_two]
yada = blah
#and_so=on
我写了一个解析器函数来更新它 b/c 我的评论字符是 '#' 而不是 ';' - 所以 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
基本上我只是逐行分解一个文本文件,填充一个新数组并将其转储回磁盘
我的错误:出于某种原因,我尝试 strcmp() 或 "==" 或 "===" 的比较似乎从未奏效......
if (trim($curKey) === trim($fkey)) { doSomething.. }
那个小虫子快把我逼疯了,因为我知道这一定很愚蠢。
任何正确方向的点都将不胜感激......
【问题讨论】:
-
你知道
parse_ini_file(),对吧?
标签: php parsing string-comparison ini