0

This string comes from ajax GET, I have decided to make a option "field".

String: width(400),height(200),age(99),string(test)

How do I split this into this kind of array:

$myArray =
[
   'width' => 400,
   'height' => 200,
   'age' => 99,
   'string => 'test'
];

Please take a note that integers has to integers, to make it easier for calculations.

3
  • Have you tried anything? Commented Jun 6, 2014 at 11:30
  • Yes I was simply looking for the "Answered" button, thanks everyone, the ajax was the most interesting, but maybe pain in the ass to maintain. Commented Jun 6, 2014 at 11:46
  • I still think complicated string parsing isn't the best solution to this. Commented Jun 6, 2014 at 12:36

4 Answers 4

2

Why not change the way you send the data?

$.ajax({
  dataType: "json",
  url: url,
  data: {width:400, height: 200, age: 99, aString: "test"},
  success: success
});

That will be easier to process in PHP. Save yourself a headache :)

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

Comments

2

The regex can probably be improved (it's not my strong point), but you could do something like this:

$string = 'width(400),height(200),age(99),string(test)';
preg_match_all('/(\w+)\((\w+)\)/', $string, $matches);

$output = array_combine($matches[1], $matches[2]);

Which outputs:

array
  'width' => string '400' (length=3)
  'height' => string '200' (length=3)
  'age' => string '99' (length=2)
  'string' => string 'test' (length=4)

1 Comment

Ended up using this since this was the shortest.
1
$str = "width(400),height(200),age(99),string(test)";
preg_match_all('/(\d|\w)+/', $str,$matches);
$array = array();
for ($i=0; $i < count($matches[0]); $i += 2) { 
    $array[$matches[0][$i]] = $matches[0][$i+1];
}
print_r($array);

RESULT:

Array
(
    [width] => 400
    [height] => 200
    [age] => 99
    [string] => test
)

Comments

0

If you are using a PHP print_r to send this variable in GET then dont do it.

You could perhaps encode the data(array) into JSON(by using json_encode) and then url_encode it and then send it in the GET variable value.

And while receiving it, do the reverse, url_decode first and then json_decode to get it in the array format you are looking for

Or else send each width, height, age and string as separate variable to save all the effort

Comments

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.