加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在php中读取类似lua的代码

发布时间:2020-12-13 21:34:42 所属栏目:PHP教程 来源:网络整理
导读:我有一个问题…… 我有这样的代码,我想用 PHP阅读它. NAME { title ( A_STRING ); settings { SetA( 15,15 ); SetB( "test" ); } desc { Desc ( A_STRING ); Cond ( A_STRING ); } } 我想要: $arr['NAME']['title'] = "A_STRING";$arr['NAME']['settings'][
我有一个问题……
我有这样的代码,我想用 PHP阅读它.

NAME
 {
    title
    (
        A_STRING
    );

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

    desc
    {
        Desc
        (
            A_STRING
        );

        Cond
        (
            A_STRING
        );  

    }
 }

我想要:

$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";

我不知道应该如何开始:/.变量并不总是相同的.
有人能给我一个关于如何解析这样一个文件的提示吗?

谢谢

解决方法

如果文件很简单,那么滚动你自己的本地解析器可能会容易得多.无论如何,最终你最终会用词法分析器编写正则表达式.这是一个快速的黑客示例:( in.txt应包含您在上面提供的输入.)

<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删除所有换行符和分号,因为它们似乎是多余的.下一部分将输入字符串分成不同的“标记”;名称,括号和之间的关系. print_r $匹配;那里看看它做了什么.

然后只有一个真正的hackish状态机(或读取for循环)通过令牌并将它们添加到树中.它还有一个堆栈,可以构建嵌套树.

请注意,此算法未经过测试.当呈现“现实生活”输入时,它可能会破裂.例如,值内的括号将导致麻烦.另请注意,它不会删除字符串中的引号.我会把这一切留给别人……

但是,正如你所要求的那样,这是一个开始:)

干杯!

PS.为方便起见,这是上面代码的输出:

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

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

        )

)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读