I have a string which looks like this:
$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $';
I need to turn it into a key value array. I don't care about the filtering and trimming. Already did that. But I can't figure out how to get the keys and values in the array.
Is that enough for you?
$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $';
$string = str_replace(['1.', ' '], '', $string); // Cleaning unescessary information
$keysAndValues = explode('$', $string);
$keys = array_filter(explode('*', $keysAndValues[0]));
$values = array_filter(explode('*', $keysAndValues[1]));
$keyPairs = array_combine($keys, $values);
var_dump($keyPairs);
array (size=3)
'key1' => string 'value1' (length=6)
'key2' => string 'value2' (length=6)
'key3' => string 'value3' (length=6)
Removes empty keys and trims values to make an orderly, usable array.
<?php
$string = '1. * key1 * key2 * key3 * $ * value1 * value2 * value3 * $';
$parts = explode("$",$string);
$keys = explode("*",substr($parts[0],2));
$values = explode("*",$parts[1]);
$arr = [];
for ($i = 0; $i < count($keys); $i++) {
if (trim($keys[$i]) !== "") {
$arr[trim($keys[$i])] = trim($values[$i]);
}
}
var_dump($arr);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.