Skip to content

Instantly share code, notes, and snippets.

@wayphorier
Created July 20, 2018 17:04
Show Gist options
  • Save wayphorier/ec252cb70c975d6de9cefea107d0a358 to your computer and use it in GitHub Desktop.
Save wayphorier/ec252cb70c975d6de9cefea107d0a358 to your computer and use it in GitHub Desktop.
Human time duration string to ISO 8601
/**
* @version 1.0.0
* Приводит строку к формату временного интервала ISO 8601 (только часы, минуты, секунды)
*
* @var string $duration_by_human Строка в понятном для человека формате (напр., 3 часа 22 минуты 15 секунд)
* @var string $period_designator Указатель временного периода
*
* @return string Отформатированная строка
*
* @see https://en.wikipedia.org/wiki/ISO_8601 Документация по ISO_8601
*/
function wph_ISO_8601_time_duration_parse( $duration_by_human ) {
$duration_by_human = preg_replace( '/\s+/', ' ', $duration_by_human ); // удаляем множественные пробелы из середины строки
$duration_by_human = explode( ' ', trim( $duration_by_human ) );
$formatted_string = 'PT';
if ( !is_numeric( $duration_by_human[0] ) )
return '';
// если в исходной строке только одно число, принимаем его за значение минут
// и возвращаем результирующую строку
if ( count( $duration_by_human ) === 1 )
return $formatted_string . $duration_by_human[0] . 'M';
foreach ( $duration_by_human as $item ) {
if ( is_numeric( $item ) ) {
$formatted_string .= $item;
} else {
$duration_unit = strtolower( mb_substr( $item, 0, 1 ) );
switch ( $duration_unit ) {
case 'ч':
case 'h':
$formatted_string .= 'H';
break;
case 'м':
case 'm':
$formatted_string .= 'M';
break;
case 'с':
case 's':
$formatted_string .= 'S';
break;
}
}
}
return $formatted_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment