0

I want to convert this string:

"B=val4, A = [val1, key=val2, val3], C=val5"

To this string:

"B=val4,A[]=asdas&A[key]=val2&A[]=val3,C=val5"

So, it can be used with parse_str()

How it must be done using preg_replace or preg_replace_callback?

preg_replace is preferable.

6
  • What is A = [val1, key=val2, val3]? A string? Commented Aug 5, 2012 at 10:59
  • Is it possible to use repeating pattern in replacement part of preg_replace? Commented Aug 5, 2012 at 11:11
  • No, that's not possible. You can't do this in a single regex. Why does it have to be a regex? Commented Aug 5, 2012 at 11:52
  • Ok then, because I must do it the hard way! This way it could be done in 2 lines of code. Commented Aug 5, 2012 at 11:53
  • Regex would definitely be the hard way in this case. Commented Aug 5, 2012 at 11:56

1 Answer 1

1

I think this won't work with regex. I wrote a little recursive function that parses your string to an array. This way you won't have to use parse_str() afterwards. I don't think this is the most elegant way, but it works. It can probably be improved.

$str = "B=val4, A = [val1, key=val2, val3], C=val5";
$i = 0;

function parse(&$i, &$str) {
    $array = array();
    $buffer = "";
    $key = "";

    while ($i < strlen($str)) {
        switch ($str[$i]) {
            case " ": //ignore spaces
                break;
            case "[": //call recursive function
                $i++;
                $buffer = parse($i, $str);
                break;
            case "]": //return sub-array
                $key ? $array[$key] = $buffer : $array[] = $buffer; // add last sub-element to array
                return $array;
                break;
            case "=": //set key and reset buffer
                $key = $buffer;
                $buffer = "";
                break;
            case ",": //add to array
                $key ? $array[$key] = $buffer : $array[] = $buffer;
                $key = "";
                $buffer = "";
                break;
            default : // add char to buffer
                $buffer .= $str[$i];
                break;
        }
        $i++;
    }
    $key ? $array[$key] = $buffer : $array[] = $buffer; // add last element to array
    return $array;
}

$array = parse($i, $str);
echo "<pre>";
print_r($array);

Output:

Array
(
    [B] => val4
    [A] => Array
        (
            [0] => val1
            [key] => val2
            [1] => val3
        )

    [C] => val5
)

Hope this helps.

1
  • It had better use $char = $str[$i] (or $char = $str{$i}) instead of $char = substr($str, $i, 1); Commented Aug 6, 2012 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.