解析(非标准)json 到 array/object

Parsing (non-standard) json to array/object

我有这样的字符串:

['key1':'value1', 2:'value2', 3:$var, 4:'with\' quotes', 5:'with, comma']

我想将它转换成这样的数组:

$parsed = [
    'key1' => 'value1',
    2      => 'value2',
    3      => '$var',
    4      => 'with\' quotes',
    5      => 'with, comma',
];

我该如何解析它? 任何提示或代码将不胜感激。

有什么不能做的?

由于您不能使用任何预建函数,例如 json_decode,您将不得不尝试找到最可能的引用场景,并用已知的子字符串替换它们。

鉴于输入数组中 所有 个值 and/or 键被封装在单引号中:

请注意:此代码未经测试

<?php
    $input = "[ 'key1':'value1', 2:'value2', 3:$var, 4:'with\' quotes', 5: '$var', 'another_key': 'something not usual, like \'this\'' ]";

    function extractKeysAndValuesFromNonStandardKeyValueString ( $string ) {

        $input = str_replace ( Array ( "\\'", "\'" ), Array ( "[DOUBLE_QUOTE]", "[QUOTE]" ), $string );
        $input_clone = $input;

        $return_array = Array ();

        if ( preg_match_all ( '/\'?([^\':]+)\'?\s*\:\s*\'([^\']+)\'\s*,?\s*/', $input, $matches ) ) {

            foreach ( $matches[0] as $i => $full_match ) {

                $key = $matches[1][$i];
                $value = $matches[2][$i];

                if ( isset ( ${$value} ) $value = ${$value};
                else $value = str_replace ( Array ( "[DOUBLE_QUOTE]", "[QUOTE]" ), Array ( "\\'", "\'" ), $value );

                $return_array[$key] = $value;

                $input_clone = str_replace ( $full_match, '', $input_clone );
            }

            // process the rest of the string, if anything important is left inside of it
            if ( preg_match_all ( '/\'?([^\':]+)\'?\s*\:\s*([^,]+)\s*,?\s*/', $input_clone, $matches ) ) {
                foreach ( $matches[0] as $i => $full_match ) {

                    $key = $matches[1][$i];
                    $value = $matches[2][$i];

                    if ( isset ( ${$value} ) $value = ${$value};

                    $return_array[$key] = $value;
                }
            }
        }


        return $return_array;

    }

此函数背后的想法是首先将非标准字符串中所有可能的引号组合替换为您可以轻松替换的内容,然后对您的输入执行标准正则表达式,然后重建所有内容以确保您正在重置先前替换的子字符串