Read lua-like code in php

I have a question ... I got such code, and I want to read it using PHP.

 NAME
 {
    title
    (
        A_STRING
    );

    settings
    {
        SetA( 15, 15 );
        SetB( "test" );
    }

    desc
    {
        Desc
        (
            A_STRING
        );

        Cond
        (
            A_STRING
        );  

    }
 }

I want:

$arr['NAME']['title'] = "A_STRING";
$arr['NAME']['settings']['SetA'] = "15, 15";
$arr['NAME']['settings']['SetB'] = "test";
$arr['NAME']['desc']['Desc'] = "A_STRING";
$arr['NAME']['desc']['Cond'] = "A_STRING";

I do not know how to start: /. Variables are not always the same. Can someone give me a hint on how to parse such a file?

thanks

+3
source share
3 answers

If the files are so simple, then it may be much easier to make your own homegrown parser. In the end, you still write regex with lexers. Here is an example of a quick hack: (in.txt should contain the input you entered.)

<pre>
<?php

$input_str = file_get_contents("in.txt");
print_r(parse_lualike($input_str));

function parse_lualike($str){    
    $str = preg_replace('/[\n]|[;]/','',$str);
    preg_match_all('/[a-zA-Z][a-zA-Z0-9_]*|[(]\s*([^)]*)\s*[)]|[{]|[}]/', $str, $matches);
    $tree = array();
    $stack = array();
    $pos = 0;
    $stack[$pos] = &$tree;
    foreach($matches[0] as $index => $token){
        if($token == '{'){
            $node = &$stack[$pos];
            $node[$ident] = array();
            $pos++;
            $stack[$pos] =  &$node[$ident];
        }elseif($token=='}'){
            unset($stack[$pos]);
            $pos--;
        }elseif($token[0] == '('){
            $stack[$pos][$ident] = $matches[1][$index];
        }else{
            $ident =  $token;
        }
    }
    return $tree;
}

?>

: preg_replace , . ""; , paranthesis. print_r $matches;, , .

( for-loop), . , .

, . , " ". , . , . - ...

, , :)

!

PS. :

Array
(
    [NAME] => Array
        (
            [title] => A_STRING   
            [settings] => Array
                (
                    [SetA] => 15, 15 
                    [SetB] => "test" 
                )

            [desc] => Array
                (
                    [Desc] => A_STRING       
                    [Cond] => A_STRING       
                )

        )

)
0

- . .

, php: lexer generator module, .

+5

This is not an answer, but a sentence:

Perhaps you can change your input code to be compatible with JSON, which has similar syntax. JSON parsers and generators are available for PHP.

http://www.json.org/

http://www.php.net/json

+2
source

Source: https://habr.com/ru/post/1709959/


All Articles