-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.

Christian
  • 124
  • 2
  • 11
  • Could make a regex.. – user3783243 Jun 10 '20 at 02: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 – Kevin Jun 10 '20 at 02: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 – Christian Jun 10 '20 at 02: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 – Kevin Jun 10 '20 at 02: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: https://3v4l.org/IGTCK – Nick Jun 10 '20 at 02:51
  • I basically just need to parse a string into a manipulable object to perform actions on, my current solution is to convert a string to an array of key-value pairs. It does not need to conform to print_r(). The output will still be a string, just modified. – Christian Jun 10 '20 at 02:57
  • Is there a better way to approach this other than converting Strings to an Array? – Christian Jun 10 '20 at 03:06
  • The question is how do you get that string and why is it formatted that way? – AbraCadaver Jun 10 '20 at 03:09
  • Did you give up? – AbraCadaver Jun 10 '20 at 23:27
  • The string is a sample input of possible incoming strings – Christian Jun 11 '20 at 00:03

1 Answers1

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.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87