What is the fastest way to convert this string to this array?
$string = 'a="b" c="d" e="f"';
Array (
a => b
c => d
e => f
)
Assuming they're always separated by spaces and the values always surrounded by quotes, you can explode() twice and strip out the quotes. There might be a faster way to do this, but this method is very straightforward.
$string = 'a="b" c="d" e="f"';
// Output array
$ouput = array();
// Split the string on spaces...
$temp = explode(" ", $string);
// Iterate over each key="val" group
foreach ($temp as $t) {
// Split it on the =
$pair = explode("=", $t);
// Append to the output array using the first component as key
// and the second component (without quotes) as the value
$output[$pair[0]] = str_replace('"', '', $pair[1]);
}
print_r($output);
array(3) {
["a"]=>
string(1) "b"
["c"]=>
string(1) "d"
["e"]=>
string(1) "f"
}
Looks like it is php script that you are referring. But please add php tag to it as suggested.
I'm not sure if there is a direct way to split it the way you want because you want the indexes to be something other than default ones.
one Algorithm to solve this problem is as follows...
I'm not sure this is fastest though.
I'll make no promises about its speed or its reliability because running an accurate benchmark requires your real data (quality and volume).
Anyhow, just to show readers another method, I'll use parse_str()
Code: (Demo)
$string = 'a="b" c="d" e="f"';
parse_str(str_replace(['"',' '],['','&'],$string),$out);
var_export($out);
This strips the double quotes and replaces all spaces with ampersands.
The method, like several others on this page, will mangle your data when a value contains a space or a double quote.
Output:
array (
'a' => 'b',
'c' => 'd',
'e' => 'f',
)
For the record, mario's answer will be the most reliable on the page.