The simplest way to do this is with preg_split
. You can use the PREG_SPLIT_DELIM_CAPTURE
flag to enable capturing the word without the surrounding quotes, and PREG_SPLIT_NO_EMPTY
to remove the empty values that arise from this particular split pattern.
$line="'PHYSICAL':3.8,'ORGANIZATIONAL':4,'TECHNICAL':2.9";
$array = preg_split("/'([^']+)':|,/", $line, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($array);
Output:
Array
(
[0] => PHYSICAL
[1] => 3.8
[2] => ORGANIZATIONAL
[3] => 4
[4] => TECHNICAL
[5] => 2.9
)
You can then post-process the array (for example using array_filter
and array_combine
) to produce something which might be more useful:
$newarray = array_combine(array_filter($array, function ($i) { return !($i % 2); }, ARRAY_FILTER_USE_KEY),
array_filter($array, function ($i) { return $i % 2; }, ARRAY_FILTER_USE_KEY));
print_r($newarray);
Output:
Array
(
[PHYSICAL] => 3.8
[ORGANIZATIONAL] => 4
[TECHNICAL] => 2.9
)
If you really want the individual variables you can do this:
for ($i = 0; $i < count($array); $i += 2) {
${'word' . intdiv($i+2, 2)} = $array[$i];
${'word' . intdiv($i+2, 2) . 'value'} = $array[$i+1];
}
echo "word1 = $word1
";
echo "word1value = $word1value
";
echo "word2 = $word2
";
echo "word2value = $word2value
";
echo "word3 = $word3
";
echo "word3value = $word3value
";
Output:
word1 = PHYSICAL
word1value = 3.8
word2 = ORGANIZATIONAL
word2value = 4
word3 = TECHNICAL
word3value = 2.9