PHP Preg_match模式从字幕srt文件中删除时间

时间:2017-07-15 13:15:17

标签: php regex preg-replace preg-match

我需要一个preg_match表达式来删除.srt字幕文件中的所有时序(作为字符串导入),但我永远无法完全掌握正则表达式模式。例如,它会改变:

5
00:05:50,141 --> 00:05:54,771
This is what was said

This is what was said

4 个答案:

答案 0 :(得分:3)

不知道你被困在哪里它只是\ d +和冒号/逗号。

$re = '/\d+.\d+:\d+:\d+,\d+\s-->\s\d+:\d+:\d+,\d+./s';
//$re = '\d+.[0-9:,]+\s-->\s[\d+:,]+./s'; //slightly compacter version of the regex
$str = '5
00:05:50,141 --> 00:05:54,771
This is what was said';
$subst = '';

$result = preg_replace($re, $subst, $str);

echo $result;

工作演示here
使用小的compacter模式,它看起来像:https://regex101.com/r/QY9QXG/2

<小时/> 而且只是为了娱乐和挑战。这是一个非正则表达式的答案。 https://3v4l.org/r7hbO

$str = "1
00:05:50,141 --> 00:05:54,771
This is what was said1

2
00:05:50,141 --> 00:05:54,771
This is what was said2

3
00:05:50,141 --> 00:05:54,771
This is what was said3

4
00:05:50,141 --> 00:05:54,771
This is what was said4
LLLL

5
00:05:50,141 --> 00:05:54,771
This is what was said5";


$count = explode(PHP_EOL.PHP_EOL, $str);

foreach($count as &$line){
    $line =  implode(PHP_EOL, array_slice(explode(PHP_EOL, $line), 2));
}

echo implode(PHP_EOL.PHP_EOL, $count);

非正则表达式将首先拆分双新行,这意味着每个新的字幕组都是数组中的新项目。
然后循环它们并在新线上再次爆炸。
不需要前两行,数组将它们切掉 如果字幕不止一行我需要合并它们。在新线上破坏了。

然后作为最后一步,再次使用双新线上的内爆来重建字符串。

  

Casimir在下面的评论中写道,我使用PHP_EOL作为新行,并且在示例中起作用   但是当在真正的srt文件上使用时,新行可能会有所不同   如果代码无法按预期工作,请尝试将PHP_EOL替换为其他新行。

答案 1 :(得分:1)

由于srt文件的格式始终相同,因此可以跳过每个行块的第一行,并在到达空行时返回结果。要做到这一点并避免将整个文件加载到内存中,您可以逐行读取文件并使用生成器:

function getSubtitleLine($handle) {
    $flag = 0;
    $subtitle = '';
    while ( false !== $line = stream_get_line($handle, 1024, "\n") ) {
        $line = rtrim($line);
        if ( empty($line) ) {
            yield $subtitle;
            $subtitle = '';
            $flag = 0;
        } elseif ( $flag == 2 ) {
            $subtitle .= empty($subtitle) ? $line : "\n$line";
        } else {
           $flag++;
        }
    }

    if ( !empty($subtitle) )
        yield $subtitle;
}

if ( false !== $handle = fopen('./test.srt', 'r') ) {
    foreach (getSubtitleLine($handle) as $line) {
        echo $line, PHP_EOL;
    }
}

答案 2 :(得分:0)

因此,考虑This is what was said以大写字母开头,可以是带标点符号的文字,我建议如下:

$re = '/.*([A-Z]{1}[A-Za-z0-9 _.,?!"\/\'$]*)/';

$str = '5
00:05:50,141 --> 00:05:54,771
This is what was said.';

preg_match_all($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);

// Print the entire match result
var_dump($matches);

答案 3 :(得分:0)

PHP代码:

$str = '5
00:05:50,141 --> 00:05:54,771
This is what was said';
$reg = '/(.{0,}[0,1]{0,}\s{0,}[0-9]{0,}.{0,}[0-9]+[0-9]+:[0-9]{0,}.{0,})/';
echo(trim(preg_replace($reg, '', $str)));