forked from leda-ferreira/vtt2srt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVtt2Srt.php
93 lines (90 loc) · 3.03 KB
/
Vtt2Srt.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/*
* Copyright (C) 2015 Leda
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace ledat;
class Vtt2Srt
{
private $input_file;
private $output_file;
public function __construct($input_file, $output_file)
{
$this->input_file = $input_file;
$this->output_file = $output_file;
}
public function run()
{
$contents = file_get_contents($this->input_file);
if ($contents === false) {
$message = "Error: Failed to read '{$this->input_file}'.";
throw new Exception($message);
}
$output = $this->convert($contents);
$result = file_put_contents($this->output_file, $output);
if ($result === false) {
$message = "Error: Failed to write to '{$this->output_file}'.";
throw new Exception($message);
}
return 1;
}
private function convert($contents)
{
$lines = $this->split($contents);
array_shift($lines); // removes the WEBVTT header
$output = '';
$i = 0;
foreach ($lines as $line) {
/*
* at last version subtitle numbers are not working
* as you can see that way is trustful than older
*
*
* */
$pattern1 = '#(\d{2}):(\d{2}):(\d{2})\.(\d{3})#'; // '01:52:52.554'
$pattern2 = '#(\d{2}):(\d{2})\.(\d{3})#'; // '00:08.301'
$m1 = preg_match($pattern1, $line);
if (is_numeric($m1) && $m1 > 0) {
$i++;
$output .= $i;
$output .= PHP_EOL;
$line = preg_replace($pattern1, '$1:$2:$3,$4' , $line);
}
else {
$m2 = preg_match($pattern2, $line);
if (is_numeric($m2) && $m2 > 0) {
$i++;
$output .= $i;
$output .= PHP_EOL;
$line = preg_replace($pattern2, '00:$1:$2,$3', $line);
}
}
$output .= $line . PHP_EOL;
}
return $output;
}
private function split($contents)
{
$lines = explode("\n", $contents);
if (count($lines) === 1) {
$lines = explode("\r\n", $contents);
if (count($lines) === 1) {
$lines = explode("\r", $contents);
}
}
return $lines;
}
}