Skip to content

Instantly share code, notes, and snippets.

@MightyPork
Created September 16, 2017 18:07
Show Gist options
  • Save MightyPork/496c81e8a28586496a1052805ef1d062 to your computer and use it in GitHub Desktop.
Save MightyPork/496c81e8a28586496a1052805ef1d062 to your computer and use it in GitHub Desktop.
<?php
/**
* Get time in seconds from user entered interval
*
* @param $time
* @return int seconds
*/
function strToSeconds($time)
{
// seconds pass through
if (preg_match('/^\d+$/', trim("$time"))) {
return intval($time);
}
$time = preg_replace('/(\s*|,|and)/i', '', $time);
$pieces = preg_split('/(?<=[a-z])(?=\d)/i', $time, 0, PREG_SPLIT_NO_EMPTY);
return array_sum(array_map('strToSeconds_do', $pieces));
}
/** @noinspection PhpUnusedPrivateMethodInspection */
function strToSeconds_do($time)
{
if (preg_match('/^(\d+)\s*(s|secs?|seconds?)$/', $time, $m)) {
return intval($m[1]);
}
if (preg_match('/^(\d+)\s*(m|mins?|minutes?)$/', $time, $m)) {
return intval($m[1]) * 60;
}
if (preg_match('/^(\d+)\s*(h|hours?)$/', $time, $m)) {
return intval($m[1]) * 60*60;
}
if (preg_match('/^(\d+)\s*(d|days?)$/', $time, $m)) {
return intval($m[1]) * 86400;
}
if (preg_match('/^(\d+)\s*(w|weeks?)$/', $time, $m)) {
return intval($m[1]) * 86400*7;
}
if (preg_match('/^(\d+)\s*(M|months?)$/', $time, $m)) {
return intval($m[1]) * 86400*30;
}
if (preg_match('/^(\d+)\s*(y|years?)$/', $time, $m)) {
return intval($m[1]) * 86400*365;
}
throw new Exception("Bad time interval: \"$time\"");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment