Skip to content

Instantly share code, notes, and snippets.

@neonxp
Created May 4, 2012 08:10
Show Gist options
  • Save neonxp/2593196 to your computer and use it in GitHub Desktop.
Save neonxp/2593196 to your computer and use it in GitHub Desktop.
Simple config file parser
<?php
function parseFile($file) {
$matches = array();
$pattern = '/(.+?)\s+(.+?)\n/';
preg_match_all($pattern, file_get_contents($file), $matches);
$matches[2] = array_map(function($value) { preg_match_all('/\G(?:^|,)(?:"([^"]*+(?:""[^"]*+)*+)"|([^",]*+))/x', $value, $ret); return (count($ret[2])>1)?$ret[2]:$ret[2][0]; } , $matches[2]);
return array_combine($matches[1], $matches[2]);
}
print_r(parseFile('input.txt'));
/**
Example file:
key1 value1
key2 value2,value2-1,value2-2,value2-3
key3 value3
key4 value4
key5 value5, value5-1
Result:
Array
(
[key1] => value1
[key2] => Array
(
[0] => value2
[1] => value2-1
[2] => value2-2
[3] => value2-3
)
[key3] => value3
[key4] => value4
[key5] => Array
(
[0] => value5
[1] => value5-1
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment