PHP how do I split this option string to this kind of array

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.

Answers


$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
)

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 :)


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)

Need Your Help

Does Apple provide a C documentation of their Operating Systems and where is it?

ios c osx documentation

I need help finding the Apple documentation (I am referring to Apple's additions to the Unix/Posix interface) (if it even exists) but it appears that there is no documentation. (or am I asking a

Android Design cancel effect of a widget to center alignment

android alignment android-linearlayout padding

I am designing an interface and I have two textview and I want to align second text to center. It is like that (red line is center of layout):

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.