Ich möchte auch noch eine Lösung posten, die auch die Verhaltensweisen für mit Quotes geklammerte Settings und Konstanten von
parse_ini_file () umsetzt. Der Code arbeitet mit regulären Ausdrücken, bei großen ini Files können also u.U. Laufzeiteinbußen erfolgen. Der Übersichtlichkeit halber habe ich des
file_get_contents () Befehl statt mal den ini String direkt angegeben.
PHP-Code:
<?
define ('HALLO_VALUE' , 'ballo');
$ini= '[zone]
name = test
position = 1
[zone]
name = "long blubb"
position = 2
[zone]
name = HALLO_VALUE
position = 2
';
// Gruppen ermitteln
preg_match_all ('/\[([^\]]+)\]([^\[]*)/', $ini, $aFound);
foreach ($aFound[1] as $iGrKey => $sGroup)
{
// doppelte Gruppennamen erweitern
@ $aGroups[$sGroup] ++;
$sGroup .= $aGroups[$sGroup] > 1 ? '_' . $aGroups[$sGroup] : '';
// Settings ermitteln
$aItems = explode ("\n", trim ($aFound[2][$iGrKey]));
foreach ($aItems as $sLine)
{
// Setting aufsplitten
list ($sKey,$sVal) = preg_split ('/\s*=\s*/', trim ($sLine));
$sVal = trim ($sVal);
// Setting mit Quotes: Quotes entfernen
if ($sVal{0} == '"' && $sVal{strlen ($sVal) - 1} == '"') $sVal = substr ($sVal, 1, -1);
// Setting mit Konstante: durch Konstante ersetzen
if (true == defined ($sVal)) $sVal = constant ($sVal);
// Settings Array füllen
$aSettings[$sGroup][$sKey] = $sVal;
}
}
print_r($aSettings);
Gibt aus:
Code:
Array
(
[zone] => Array
(
[name] => test
[position] => 1
)
[zone_2] => Array
(
[name] => long blubb
[position] => 2
)
[zone_3] => Array
(
[name] => ballo
[position] => 2
)
)