Skip to content

Instantly share code, notes, and snippets.

@jamiehs

jamiehs/gist:9824788

Created Mar 28, 2014
Embed
What would you like to do?
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
You can’t perform that action at this time.