Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

clevonnoel's avatar

Parse Date Value - 1d 4h 3m 7s

Given i have the value 1d 4h 3m 7s how can I parse the value to return an array like

array([
    'day' =>  1,
    'hours' => 4,
    'minutes' => 3,
    'seconds' =>7
])

0 likes
4 replies
tykus's avatar
$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];
});
1 like
tykus's avatar
tykus
Best Answer
Level 104

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);
1 like

Please or to participate in this conversation.