ISO 8601 Parser for PHP
<?php | |
/** | |
* Parse an ISO 8601 duration string | |
* @return array | |
* @param string $str | |
**/ | |
function parseDuration($str) | |
{ | |
$result = array(); | |
preg_match('/^(?:P)([^T]*)(?:T)?(.*)?$/', trim($str), $sections); | |
if(!empty($sections[1])) | |
{ | |
preg_match_all('/(\d+)([YMWD])/', $sections[1], $parts, PREG_SET_ORDER); | |
$units = array('Y' => 'years', 'M' => 'months', 'W' => 'weeks', 'D' => 'days'); | |
foreach($parts as $part) | |
{ | |
$result[$units[$part[2]]] = $part[1]; | |
} | |
} | |
if(!empty($sections[2])) | |
{ | |
preg_match_all('/(\d+)([HMS])/', $sections[2], $parts, PREG_SET_ORDER); | |
$units = array('H' => 'hours', 'M' => 'minutes', 'S' => 'seconds'); | |
foreach($parts as $part) | |
{ | |
$result[$units[$part[2]]] = $part[1]; | |
} | |
} | |
return($result); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment