-1

I'm new to PHP but coming from Java & JavaScript. I have a string which I think resembles an Array?

[name] => John
[lastname] => Smith
[age] => 1.00
[amount] => 21.00
[birthday] => 6/9/2020

How would I parse this into an Array object so I can perform actions on each "key"?

parse_str() seems to fail with this, and so does explode() as it does not produce a "key-value" pair I can easily iterate over.

10
  • Could make a regex.. Commented Jun 10, 2020 at 2:42
  • do you have control over the response? you could just use json, then you could just use the built in library for it to be converted into a data type on the other side Commented Jun 10, 2020 at 2:43
  • @Kevin can you elaborate a bit more? Do you mean converting strings to json instead of arrays? I have a test whether the input string is able to be decoded using json_decode(), the example above cannot sadly Commented Jun 10, 2020 at 2:46
  • @ChristianGarrovillo im not sure why would someone give a server response of a print_r, but if you have no control over it, you'll have to resort to a print_r converter of sorts, like the duplicate question above, there are answers in there that you could use Commented Jun 10, 2020 at 2:50
  • You need to do a bit of hacking to get that string to work with the function that was in the question I originally closed this with as it is very fussy about the input format. Here's a working example: 3v4l.org/IGTCK Commented Jun 10, 2020 at 2:51

1 Answer 1

0

There are lots of ways to manipulate that string to get it to parse into an array. You can convert it to ini syntax:

$result = parse_ini_string(str_replace(['[', '=>'], ['data[', '='], $string))['data'];

Or you could convert to a query string and use parse_str or any number of other formats that would be more complex like JSON or quoting the keys and values and running eval:

eval('$result = [' . preg_replace('/\[([^[]+)\] => (.*)/', "'$1' => '$2',", $string)  . '];');

The best way would be to generate a usable format such as JSON instead of the format you have.

Sign up to request clarification or add additional context in comments.

2 Comments

Would parsing the string to a JSON instead of an Array be a better way?
Doesn’t matter I meant getting it as JSON at the beginning would be better.

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.