Created
March 28, 2014 03:37
-
-
Save jamiehs/9824788 to your computer and use it in GitHub Desktop.
ISO 8601 Parser for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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