John Davidson

regex - php: better way to split string into associative array

0 comments
Message:


I have a string like this:


"ALARM_ID/I4=1010001 ALARM_STATE/U4=eventcode ALARM_TEXT/A=WMR_MAP_EXPORT LOTS/A[1]=[ STEFANO ] ALARM_STATE/U1=1 WAFER/U4=1 VI_KLARF_MAP/A=/test/klarf.map KLARF_STEPID/A=StepID KLARF_DEVICEID/A=DeviceID KLARF_EQUIPMENTID/A=EquipmentID KLARF_SETUP_ID/A=SetupID RULE_ID/U4=1234 RULE_FORMULA_EXPRESSION/A=a < b && c > d RULE_FORMULA_TEXT/A=1 < 0 && 2 > 3 RULE_FORMULA_RESULT/A=FAIL TIMESTAMP/A=10-Nov-2020 09:10:11 99999999"

and my goal is to split into an associative array:


Array
(
[ALARM_ID/I4] => 1010001
[ALARM_STATE/U4] => eventcode
[ALARM_TEXT/A] => WMR_MAP_EXPORT
[LOTS/A[1]] => [ STEFANO ]
[ALARM_STATE/U1] => 1
[WAFER/U4] => 1
[VI_KLARF_MAP/A] => /test/klarf.map
[KLARF_STEPID/A] => StepID
[KLARF_DEVICEID/A] => DeviceID
[KLARF_EQUIPMENTID/A] => EquipmentID
[KLARF_SETUP_ID/A] => SetupID
[RULE_ID/U4] => 1234
[RULE_FORMULA_EXPRESSION/A] => a < b && c > d
[RULE_FORMULA_TEXT/A] => 1 < 0 && 2 > 3
[RULE_FORMULA_RESULT/A] => FAIL
[TIMESTAMP/A] => 10-Nov-2020 09:10:11 99999999
)

The unique (but maybe dirties) way that I found is through this script:


<?php
$msg = "ALARM_ID/I4=1010001 ALARM_STATE/U4=eventcode ALARM_TEXT/A=WMR_MAP_EXPORT LOTS/A[1]=[ STEFANO ] ALARM_STATE/U1=1 WAFER/U4=1 VI_KLARF_MAP/A=/test/klarf.map KLARF_STEPID/A=StepID KLARF_DEVICEID/A=DeviceID KLARF_EQUIPMENTID/A=EquipmentID KLARF_SETUP_ID/A=SetupID RULE_ID/U4=1234 RULE_FORMULA_EXPRESSION/A=a < b && c > d RULE_FORMULA_TEXT/A=1 < 0 && 2 > 3 RULE_FORMULA_RESULT/A=FAIL TIMESTAMP/A=10-Nov-2020 09:10:11 99999999";
$split = explode("=", $msg);
foreach($split as $k => $s) {
$s = explode(" ", $s);
$keys[] = array_pop($s);
if ($s) $values[] = implode(" ", $s);
}
/*
* this is needed if last parameter TIMESTAMP does not have ' ' (spaces) into value
*/
if (count($values) + 2 == count($keys)) array_push($values, array_pop($keys));
else $values[ count($values) - 1 ] .= " " . array_pop($keys);
$params = array_combine($keys, $values);
print_r($params);
?>

Do you see a better way to split it maybe using regular expression or a different (elegant?) approach?



My Answer:
$string = "key1=value1&key2=value2&key3=value3";

// Initialize an empty array to store the key-value pairs
$data = [];

// Split the string by "&" to get individual key-value pairs
$pairs = explode("&", $string);

// Loop through each key-value pair and split it by "=" to get the key and value
foreach ($pairs as $pair) {
list($key, $value) = explode("=", $pair);
$data[$key] = $value;
}

// Print the associative array
print_r($data);

Rate this post

4 of 5 based on 8208 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us