$str = "1d 4h 3m 7s";
// Create a map between the time unit initial and the word, e.g. d => days
$map = [
'd'=>'days',
'h'=>'hours',
'm'=>'minutes',
's'=>'seconds'
];
// Split the string into digit/letter pairs, assign the resulting array to a collection instance and flatMap over it
collect(explode(' ', $str))->flatMap(function($timeUnit) use ($map) {
// array destructuring to assign to $digit and $letter
list($digit,$letter) = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$timeUnit);
// create an associative array with mapped word as key and digit as value
return [$map[$letter] => $digit];
});
I would probably refactor the following further, but it will get you started for now:
// Original string
$str = "1 d 4h 3 m 7 s";
// Define a mapping to convert the letters into words
$map = [
'd' => 'days',
'h' => 'hours',
'm' => 'minutes',
's' => 'seconds'
];
// Allows for the presence of zero or more spaces between the digit/letter pairs
preg_match_all('/([0-9]+)\s*([a-z]+)/', $str, $matches);
// Destructure the matches into 3 variables (the first can be ignored)
list($ignore, $digits, $letters) = $matches;
// Map the letters into words
$keys = array_map(function($letter) use ($map) {
return $map[$letter];
}, $letters);
// Combine the two arrays into an associative array
$result = array_combine($keys, $digits);