0

I have a complex jquery serialized string and I can not parse it in php. I use jquery repeater in my form and this serialized string is obtained with jQuery serialize:

[0][mix][]=on&[0][field]=i.faName&[0][condition]=like&[0][value]=joe&[1][field]=i.enName&[1][condition]=not like&[1][value]=sarah

I have tried these and to no avail:

json_decode
parse_str
unserialize
Ethan
  • 881
  • 8
  • 14
  • 26
hyalavi
  • 3
  • 1
  • This seems to be a url-encoded string. That might be what you need to look at. How this string was created though might be worth looking at. If you can change it to be a JSON string it will be much easier to work with! – Skudd Aug 09 '23 at 15:35
  • @Skudd That's what jQuery `.serialize()` returns, a URL-encoded string. – Barmar Aug 09 '23 at 15:37
  • 3
    That serialized string doesn't look correct, there are no names before `[0]`, `[1]`, etc. – Barmar Aug 09 '23 at 15:39
  • PHP will parse it into `$_POST`. What does `var_dump($_POST)` look like? – Barmar Aug 09 '23 at 15:39
  • This might be of help: https://stackoverflow.com/a/1186309/244070 – Skudd Aug 09 '23 at 15:40

1 Answers1

0

Took a stab at this and came up with the following. Note that this might not work completely for your use case, but it should give you a good starting point. If you're unsure of the $matches array, just print_r() it and you'll get a sense for what it is and how it relates to the PCRE.

<?php

$value = '[0][mix][]=on&[0][field]=i.faName&[0][condition]=like&[0][value]=joe&[1][field]=i.enName&[1][condition]=not like&[1][value]=sarah';

$result = [];

$pairs = explode('&', $value);

foreach ($pairs as $pair)
{
    preg_match('/^\[(?<objectId>\d+)\]\[(?<name>.*?)\](?<otherArgs>.*?)=(?<value>.*?)$/', $pair, $matches);
        
    if (!isset($result[$matches['objectId']])) {
        $result[$matches['objectId']] = [];
    }

    if (!isset($result[$matches['objectId']][$matches['name']])) {
        if ($matches['otherArgs'] == null) {
            $result[$matches['objectId']][$matches['name']] = $matches['value'];
        } elseif ($matches['otherArgs'] == '[]')  {
            $result[$matches['objectId']][$matches['name']] = [$matches['value']];
        }
    } elseif ($matches['otherArgs'] == '[]') {
        $result[$matches['objectId']][$matches['name']][] = $matches['value'];
    } else {
        $result[$matches['objectId']][$matches['name']] = [$result[$matches['objectId']][$matches['name']], $matches['value']];
    }
}

print_r($result);

Sample output:

Array
(
    [0] => Array
        (
            [mix] => Array
                (
                    [0] => on
                )

            [field] => i.faName
            [condition] => like
            [value] => joe
        )

    [1] => Array
        (
            [field] => i.enName
            [condition] => not like
            [value] => sarah
        )

)
Skudd
  • 684
  • 2
  • 12
  • 28