0

I need help cleaning up a text file using PHP. The file is being processed afterwards by another function that requires the text to be formatted in a certain way.

Original closed caption text:

1
00:00:22,767 --> 00:00:24,634
line text 1
line text 2
line text 3

2
00:00:26,767 --> 00:00:28,634
line text 1
line text 2
line text 3

I need the line text all on one line. eg.

1
00:00:22,767 --> 00:00:24,634
line text 1 line text 2 line text 3

2
00:00:26,767 --> 00:00:28,634
line text 1 line text 2 line text 3

I would love some help/input. I am just having trouble gettign into the right head space. Thanks.

1 Answers1

0

You can read the file like here: Read a plain text file with php And then process each line and write it to another file. If you want that the modifications overwrite the original file, yo can make a copy of it, read from the copy and write the changes to the original one. Something like this should work:

<?php

$oldFile = fopen('oldFile.txt','r');
$newFile = fopen('newFile.txt', 'w');
$newLine = false;
while ($line = fgets($oldFile)) {
    //If is the number of the caption
    if(preg_match('/^\d+$/',$line)) {
        if(!newLine) {
            fwrite($newFile,'\n');  
        }
        fwrite($newFile, $line.'\n');
        $newLine = true;
    }
    //if it is the minutes label
    //00:00:22,767 --> 00:00:24,634
    else if(preg_match('/^\d{2}:\d{2}:\d{2}.\d{3} --> \d{2}:\d{2}:\d{2}.\d{3}$/',$line)) {
        if(!newLine) {
            fwrite($newFile,'\n');  
        }
        fwrite($newFile, $line.'\n');
        $newLine = true;
    }
    else {
        fwrite($newFile,$line.' ');
        $newLine = false;
    }
}
fclose($newFile)
fclose($oldFile);
?>
Community
  • 1
  • 1
Simon Soriano
  • 803
  • 12
  • 19