Skip to content

Instantly share code, notes, and snippets.

@jamiehs
Created March 28, 2014 03:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiehs/9824788 to your computer and use it in GitHub Desktop.
Save jamiehs/9824788 to your computer and use it in GitHub Desktop.
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