-1

I have string like this:

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

And I want to convert it to an array like this:

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

How can I parse that? Any tips or codes will be appreciated.

What can't be done?

  • Using standard json parsers
  • eval()
  • explode() by , and explode() by :
tempoman
  • 13
  • 2
  • 1
    unfortunately the string is not json. there are unquoted strings in it [3:$var] in the example above. – tempoman Nov 19 '18 at 17:50
  • You will get a better response from the community if you attempt to write something in code. Otherwise it looks like you are asking a **DIFM** question – RiggsFolly Nov 19 '18 at 17:53
  • @tempoman in your question you have specified, at index 3 of the input array: 3:$var. Is this a typo? Does it actually is 3: '$var' ? I mean, $var is valorized from a PHP variable or is "literally" '$var' ? – Maurizio Nov 19 '18 at 17:54
  • Split string by `,` delimiter and loop through array, and in loop split content of every item by `:` delimiter and store values in new array. – Mohammad Nov 19 '18 at 17:58
  • @Maurizio no it's not a type, $var is a string value and can be any valid php variable (like $arr['hello']['...'] too, otherwise it was a valid json. – tempoman Nov 19 '18 at 17:58
  • @Mohammad strings can have a `,` too, I've updated the question. – tempoman Nov 19 '18 at 18:01
  • @RiggsFolly Actually I don't know how to fix the problem, of course If I had a clue, I would solve it by myself (as I asked for "any tips" in my question). Anyway, thank you for your comment, I updated the question with `What can't be done?` part. – tempoman Nov 19 '18 at 18:12

1 Answers1

1

As you cannot use any pre-built function, like json_decode, you'll have to try and find the most possible scenarios of quoting, and replace them with known substrings.

Given that all of the values and/or keys in the input array are encapsulated in single quotes:

Please note: this code is untested

<?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;

    }

The idea behind this function is to first replace all the possible combinations of quotes in the non-standard string with something you can easily replace, then perform a standard regexp against your input, then rebuild everything assuring you're resetting the previously replaced substrings

Maurizio
  • 469
  • 1
  • 4
  • 11