javascript - 从 .SRT 文件中添加或减去秒数

标签 javascript php jquery regex srt

我已经搜索过了,没有找到类似的东西。
我想要实现的是创建一个简单的 PHP/js/jq 脚本,它可以从 .srt 文件中添加或减去秒数。我不确定正则表达式是我应该用来实现它还是其他东西。
用户将上传/复制 srt 文件的文本,然后将秒数添加到他们想要从 SRT 中添加或减去秒数的输入框。

例如,如果用户将 +4 秒添加到以下 srt 文件:

0
00:00:04,594 --> 00:00:10,594
this is a subtitle

1
00:00:40,640 --> 00:00:46,942
this is another subtitle

2
00:02:05,592 --> 00:02:08,694
this is one more subtitle

它应该是这样的:

0
00:00:08,594 --> 00:00:14,594
this is a subtitle

1
00:00:44,640 --> 00:00:50,942
this is another subtitle

2
00:02:09,592 --> 00:02:12,694
this is one more subtitle

最佳答案

这是一个 PHP 解决方案,它是您指定的语言之一。

如果您可以将要应用的时间偏移量表示为字符串,则可以使用DateTime 方法DateTime::modify() , DateTime::createFromFormat()preg_replace_callback()实现你想做的事。

SubRip Wikipedia entry指定时间码格式为:

hours:minutes:seconds,milliseconds

所以我们可以写一个正则表达式来捕捉这个;例如:/(\d+:\d+:\d+,\d+)/ - 尽管您可能希望对其进行优化。

假设您的 .srt 文件被读入字符串 $srt,并且您想将时间增加 5 秒:

<?php

$srt = <<<EOL

0
00:00:04,594 --> 00:00:10,594 this is a subtitle

1
00:00:40,640 --> 00:00:46,942 this is a subtitle

2
00:02:05,592 --> 00:02:08,694 this is a subtitle
EOL;

$regex  = '/(\d+:\d+:\d+,\d+)/';
$offset = '+5 seconds';

$result = preg_replace_callback($regex, function($match) use ($offset) {
    $dt = DateTime::createFromFormat('H:i:s,u', $match[0]);
    $dt->modify($offset);
    return $dt->format('H:i:s,u');
}, $srt);

echo $result;

在每个 $match 上,使用 DateTime::createFromFormat() 将匹配的时间码转换为 DateTime 对象,然后您可以修改并重新格式化为表示偏移时间的字符串。

您可以在 DateTime::modify() 中使用各种偏移值,包括但不限于:+1 分钟-30 秒1 小时 2 分钟 等等。阅读链接文档了解更多详情。

这会产生:

0
00:00:09,594000 --> 00:00:15,594000 this is a subtitle

1
00:00:45,640000 --> 00:00:51,942000 this is a subtitle

2
00:02:10,592000 --> 00:02:13,694000 this is a subtitle

希望这有帮助:)

关于javascript - 从 .SRT 文件中添加或减去秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446399/

相关文章:

php - 从jquery ajax post获取php中的json字符串

javascript - 在 javascript 中将 onclick 事件设置为 C# URL 操作?

php - Drupal 是如何工作的?

javascript - php 不显示来自 AJAX 的变量

php - SQL 查询构造

php - 如何从php数组中检索不包括特定元素的随机元素

javascript - 根据url滚动网页

javascript - 当用户单击任何数字时停止计时器/自动流程

javascript - 在 Accordion 中设置事件部分

javascript - 在嵌入标签上隐藏一个 div