Hi I got the following string:
info:infotext,
dimensions:dimensionstext
and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.
I want to put the info as the key and he infotext as the value into an array like this:
Array {
[info] => infotext
[dimensions] => dimensionstext
}
LF-DevJourney
28.6k30 gold badges170 silver badges322 bronze badges
asked Mar 27, 2017 at 9:27
Kuubs
1,3401 gold badge17 silver badges43 bronze badges
2 Answers 2
<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));
foreach($array as $v)
{
$o[$v[0]] = $v[1];
}
print_r($o);
answered Mar 27, 2017 at 9:37
LF-DevJourney
28.6k30 gold badges170 silver badges322 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use array_chunk and array_combine
<?php
$input = 'info:infotext,
dimensions:dimensionstext';
$chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
print_r($result);
answered Mar 27, 2017 at 9:32
Nishant Nair
1,9971 gold badge14 silver badges18 bronze badges
Comments
lang-php