2017-07-15 45 views
0

我需要一个preg_match表达式来从.srt字幕文件中删除所有的时间(导入为一个字符串),但我永远无法让我的脑袋回合正则表达式模式。因此,例如它会改变:PHP Preg_match模式从字幕srt文件中删除时间

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

This is what was said 
+1

你有几个例子,所以我们可以清楚地看到他们是如何变化吧。 – Doug

+1

是否这样? https://regex101.com/r/QY9QXG/1 – Andreas

+0

@Doug他们真的没有。第一个数字是字幕的计数,新行,然后是开始时间和结束时间。然后是新行和文本。 – Andreas

回答

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
与小更紧凑的模式,它看起来像: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); 

的非正则表达式将第一分割双新线,这意味着每一个新的字幕组是在阵列中的新项目。
然后通过它们循环并在新行上再次爆炸。
前两行是不需要的,array将它们分开。
如果字幕不止一行,我需要合并它们。用新线路解决这个问题。

然后,作为最后一步,重新生成字符串,使用两行新的implode。

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

+0

感谢Aravindh。忘记了链接。 – Andreas

+0

任何人可以评论downvote?我做错了什么? – Andreas

+0

这绝对是答案...不能理解那一个...... – funilrys

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); 
+0

请记住它是字幕文件。就像在电影和电视节目中看到的副标题一样。因此,我认为需要超过A-Z。 – Andreas

+0

Right @Andreas ... – funilrys

+0

您如何看待我的更新@Andreas? – funilrys

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))); 
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; 
    } 
}