- https://www.codewars.com/kata/5e454bf176551c002ee36486 Apply offset to subtitles.
Started at 22:01 16.09.2020 Wednesday Sep.
Finished at 22:59 16.09.2020 Wednesday Sep. (0hrs 58minutes)
Started at 22:01 16.09.2020 Wednesday Sep.
Finished at 22:59 16.09.2020 Wednesday Sep. (0hrs 58minutes)
<?php | |
# https://www.codewars.com/kata/5e454bf176551c002ee36486 Apply offset to subtitles. | |
function subs_offset_apply($string, $offset){ | |
$s = 1000; $m = $s * 60; $h = $m * 60; $n = "Invalid offset"; | |
echo "$string \n $offset \n"; | |
$to_ms = function($hrs,$mins,$scnds,$mscnds) use ($s, $m, $h){ | |
return $hrs*$h + $mins * $m + $scnds * $s + $mscnds; | |
}; | |
$to_time = function($mscnds) use ($s, $m, $h){ | |
$answer = []; | |
$answer[] = $mscnds % $s; | |
$mscnds -= $mscnds % $s; | |
$answer[] = ($mscnds % $m) / $s; | |
$mscnds -= $mscnds % $m; | |
$answer[] = ($mscnds % $h) / $m; | |
$mscnds -= $mscnds % $h; | |
$answer[] = $mscnds / $h; | |
return sprintf("%02d:%02d:%02d,%03d",...array_reverse($answer)); | |
}; | |
# 99:59:59,999 | |
$max = $to_ms(99,59,59,999); | |
$y = $to_time($max); | |
echo "$y - test max\n"; | |
# "01:09:02,684 --> 01:09:03,601 Run Forrest, run!" | |
$check = preg_match('/^(\d+):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+) (.*)$/',$string,$match); | |
if(!$check) throw new Exception('Regex does not match.'); | |
$s_h = intval($match[1],10); | |
$s_m = intval($match[2],10); | |
$s_s = intval($match[3],10); | |
$s_x = intval($match[4],10); | |
$e_h = intval($match[5],10); | |
$e_m = intval($match[6],10); | |
$e_s = intval($match[7],10); | |
$e_x = intval($match[8],10); | |
$text = $match[9]; | |
$start_total = $to_ms($s_h,$s_m,$s_s,$s_x); | |
$end_total = $to_ms($e_h,$e_m,$e_s,$e_x); | |
$start_new = $start_total + $offset; | |
$end_new = $end_total + $offset; | |
$start_init = $to_time($start_total); | |
$end_init = $to_time($end_total); | |
$start_changed = $to_time($start_new); | |
$end_changed = $to_time($end_new); | |
echo "$string\n"; | |
echo "$start_init --> $end_init $text\n"; | |
echo "$start_changed --> $end_changed $text\n"; | |
if($start_new < 0 || $end_new < 0){ | |
echo "Less then zero.\n"; | |
return $n; | |
} | |
if($start_new > $max || $end_new > $max){ | |
echo "Greater than max.\n"; | |
return $n; | |
} | |
return "$start_changed --> $end_changed $text"; | |
} |