Convert a name=value pairs string into array
11
Convert an irregular name=value pair string into a formatted array.
function pairstr2Arr ($str, $separator='=', $delim=',') {
$elems = explode($delim, $str);
foreach( $elems as $elem => $val ) {
$val = trim($val);
$nameVal[] = explode($separator, $val);
$arr[trim(strtolower($nameVal[$elem][0]))] = trim($nameVal[$elem][1]);
}
return $arr;
}
// Example usage:
$string = '1=one, 2=two , 3=three , Site=apple , name= Joe Bloggs';
$array = pairstr2Arr($string);
echo '<pre>';
print_r($array);
echo '</pre>';>
// Returns:
Array
(
[1] => one
[2] => two
[3] => three
[site] => apple
[name] => Joe Bloggs
)
$elems = explode($delim, $str);
foreach( $elems as $elem => $val ) {
$val = trim($val);
$nameVal[] = explode($separator, $val);
$arr[trim(strtolower($nameVal[$elem][0]))] = trim($nameVal[$elem][1]);
}
return $arr;
}
// Example usage:
$string = '1=one, 2=two , 3=three , Site=apple , name= Joe Bloggs';
$array = pairstr2Arr($string);
echo '<pre>';
print_r($array);
echo '</pre>';>
// Returns:
Array
(
[1] => one
[2] => two
[3] => three
[site] => apple
[name] => Joe Bloggs
)






And if you must use commas just str_replace it with &.
I would also rewrite your function, adding a second optional parameter - delimiter.
function pairstr2Arr($string, $delimiter = ',') {
$pairs = explode($delimiter, $string);
...
}