Skip to content

Instantly share code, notes, and snippets.

@jkaflik
Created May 29, 2013 12:26
Show Gist options
  • Save jkaflik/5669904 to your computer and use it in GitHub Desktop.
Save jkaflik/5669904 to your computer and use it in GitHub Desktop.
<?php
$configString = 'opcja1 wartość;
opcja2 wartość;
blok1 {
opcja3 wartość;
opcja4 wartość;
blok1.1 {
opcja5 wartość;
}
}
blok2 {
opcjax 11;
}';
function parse_config_block( $input, &$n = 0 )
{
$output = array();
$currentString = '';
for ( ; $n < strlen( $input ); $n++ )
{
$char = $input[ $n ];
if ( $char == "\n" )
{
$currentString = '';
continue;
}
if ( $char == ";" )
{
$currentString = trim( $currentString );
if ( empty( $currentString ) )
{
throw new Exception('Invalid statement');
}
$statement = explode(' ', $currentString, 2);
if ( count( $statement ) < 2 )
{
throw new Exception('Invalid statement');
}
$key = array_shift( $statement );
$output[ $key ] = array_shift($statement);
$currentString = '';
continue;
}
if ( $char == '{' )
{
if ( empty( $currentString ) )
{
throw new Exception('Invalid statement at line');
}
$blockName = trim( $currentString );
$n++;
$output[ $blockName ] = parse_config_block( $input, $n );
continue;
}
if ( $char == '}' )
{
return $output;
}
$currentString .= $char;
}
return $output;
}
var_dump( parse_config_block( $configString ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment