将字符串解析为有效的php对象

时间:2012-03-21 17:48:51

标签: php regex parsing

我收到了这样的字符串:

{
    key1 = "some value";
    key2 = "some value";
    key3 = "some value";
    key4 = 1235678;
}

我需要解析它,使它成为一个有效的php对象或数组。我认为Regex是要走的路,但我真的很擅长。

3 个答案:

答案 0 :(得分:1)

你基本上必须自己解析它。幸运的是,您至少可以先使用token_get_all将其分解为令牌:

$str = '{
    key1 = "some= value1";
}';
print_r(token_get_all('<?php ' . $str . ' ?>'));

/* output:

Array
(
    [0] => Array
        (
            [0] => 368
            [1] =>  1
        )

    [1] => {
    [2] => Array
        (
            [0] => 371
            [1] => 

            [2] => 1
        )

    [3] => Array
        (
            [0] => 307
            [1] => key1
            [2] => 2
        )

    [4] => Array
        (
            [0] => 371
            [1] =>  
            [2] => 2
        )

    [5] => =
    [6] => Array
        (
            [0] => 371
            [1] =>  
            [2] => 2
        )

    [7] => Array
        (
            [0] => 315
            [1] => "some= value1"
            [2] => 2
        )

    [8] => ;
    [9] => Array
        (
            [0] => 371
            [1] => 

            [2] => 2
        )

    [10] => }
    [11] => Array
        (
            [0] => 371
            [1] =>  
            [2] => 3
        )

    [12] => Array
        (
            [0] => 370
            [1] => ?>
            [2] => 3
        )

)

*/

然后,您可以遍历返回的数组,查找=;以查找分配和结束语句。请注意,它会解析要插补的令牌,例如,key1 = "some $value"将解析出$value

答案 1 :(得分:1)

尝试这个..疯狂但它的确有效(无论如何我会推荐JSON)

    $string = '{
        key1 = "some value";
        key2 = "some value";
        key3 = "some value";
        key4 = 1235678;
    }' ;



    var_dump(parseString($string));

    function parseString($string)
    {
        $output = array();
        $string = str_replace(array("{","}"), "", $string);
        $string = explode(";",$string) ;

        foreach($string as $values)
        {
            $values = trim($values);

            if(strpos($values, "="))
            {
                list($key,$value) = explode("=",$values);
                $value = trim($value) ;
                $value = trim($value,"\"") ;
                $key = trim($key);
                $output[$key] = $value;
            }
        }

        return $output ;
    }

结果

    array
    'key1 ' => string 'some value' (length=10)
    'key2 ' => string 'some value' (length=10)
    'key3 ' => string 'some value' (length=10)
    'key4 ' => string '1235678' (length=7)

答案 2 :(得分:0)

$strA = array_filter(explode(";",YourString));
foreach($strA as $combineValue){
   $cV = array_filter(explode("=",combineValue));
    echo $cv[0].'--'.$cv[1];
}

目前没有资源来测试代码段。但我认为它应该会有所帮助。

这是你的响应的验证JSON转换(可能会帮助你)如果你能得到json respose会很好:

{
"key1": "some value",
"key2": "some value",
"key3": "some value",
"key4": 1235678
}