PHP - remove entire line in subtitle that contain with specific word

Viewed 166

I have sets of specific words that i want to detect them in subtitle and then remove entire line with regex:

$forbiddenWords = [
    'Ads',
    'Download',
    //
];

$file = file_get_contents('example.srt');

foreach ($forbiddenWords as $word) {
    $file .= preg_replace("/\d{3}(?!.*?-)[\s\S]*?$word\[\s\S]*?(?=\d)/", '', $file);
}

Lines of subtitle:

1
00:00:39,243 --> 00:00:45,820
This line is ok

2
00:00:46,243 --> 00:00:51,820
This line with
"Ads" word should be deleted
and next line

3
00:01:04,243 --> 00:01:05,820
This line with
"Download" word should be deleted
and next line

4
00:01:08,664 --> 00:01:12,331
An ok line

The output i want :

1
00:00:39,243 --> 00:00:45,820
This line is ok

2
00:00:46,243 --> 00:00:51,820


3
00:01:04,243 --> 00:01:05,820


4
00:01:08,664 --> 00:01:12,331
An ok line

My regex doesn't work and it captures multiple lines DEMO REGEX

1 Answers

You may use

preg_replace('~^(\d+\R(\d{2}:\d{2}:\d{2},\d{3}) --> (?2))(?:\R(?!(?1)).*)*?\b(?:Download|Ads)\b[\s\S]*?(?=\s*(?:(?1)|\z))~mu', '$1', $text)

See the regex demo

Details

  • ^ - start of a line (due to m flag)
  • (\d+\R(\d{2}:\d{2}:\d{2},\d{3}) --> (?2)) - Group 1 (the subtitle ID + timespan line):
    • \d+ - 1+ digits
    • \R - a line break char sequence
    • (\d{2}:\d{2}:\d{2},\d{3}) - Group 2 (timestamp): 2 digits, :, 2 digits, :, 2 digits, comma, three digits
    • --> - literal string
    • (?2) - timestamp pattern
  • (?:\R(?!(?1)).*)*? - any 0 or more (but as few as possible) lines that do not start with the subtitle ID + timespan pattern
  • \b(?:Download|Ads)\b - whole word Download or Ads (add more if you need)
  • [\s\S]*?(?=\s*(?:(?1)|\z)) - any 0 or more chars as few as possible, up to the first occurrence of 0+ whitespaces followed with timespan pattern or end of the whole string.
Related