0

I want to convert a string to an array. I want an array that has a sub array like this :

my string :

field=3,icon=[class='test',svg=null],test=[pass='345',username='salar']

to :

array("field"=> 3,"icon"=> [ "class" =>  "test", "svg" => null ], "test"=> [ "pass" =>  "345", "username" => 'salar' ] )
3
  • 2
    Hi! Welcome to StackOverflow! Please read our tour to get a better understanding about how to ask a good question. Please show us what you've tried. Commented Apr 2, 2021 at 14:50
  • Where is the input format from? Instead maybe it could be better to use some more common like JSON? Commented Apr 2, 2021 at 14:51
  • 3
    Where is this string coming from? Maybe instead of generating a string like this, you could have it generate a JSON string or something? Commented Apr 2, 2021 at 14:51

1 Answer 1

1

I would highly suggest changing the string format being generated. It's better to use an existing format like JSON than to create/parse your own format.

Speaking of JSON, one way to "parse" this format is to convert it to JSON and then parse that.

So, convert the = to :, wrap all keys (and values) in "", convert [] to {}, and then wrap the whole thing in {}.

<?php
$data = "field=3,icon=[class='test',svg=null],test=[pass='345',username='salar']";

// Fix quotes
$jsonData = str_replace("'", '"', $data);

// Convert arrays to objects
$jsonData = str_replace(['[', ']'], ['{', '}'], $jsonData);

// Fix keys
$jsonData = preg_replace("/(^|,|{)(.+?)=/", '$1"$2":', $jsonData);

// Parse as JSON
$result = json_decode('{' . $jsonData . '}', true);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! This code was great and it was exactly what I wanted

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.