Last active
February 22, 2020 15:39
-
-
Save halgatewood/0dbad64e6404c582e9b01eeb946ed3ae to your computer and use it in GitHub Desktop.
PHP Function to Convert SBV to SRT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convert_sbv_to_srt( $lines ) | |
{ | |
if( !$lines ) return ""; | |
// BREAK LINES ON RETURN | |
$lines = explode("\n", $lines); | |
// ADD A BLANK SPACE AT THE BEGINNING, | |
// I USE BLANK SPACES TO DETERMINE BETWEEN THE DIFFERENT TEXT BLOCKS | |
array_unshift($lines,""); | |
// RETURN VARIABLE | |
$srt = ""; | |
$num = 1; | |
foreach( $lines as $c => $line ) | |
{ | |
// IF LINE IS EMPTY, SHOULD BE A NEW BLOCK | |
if( !$line ) | |
{ | |
// DOING THE WHOLE BLOCK FROM INSIDE THE EMPTY LINE | |
// SET NUMBER OF BLOCK | |
$srt .= $num . "\n"; | |
// GRAB THE TIME | |
$time = $lines[$c + 1]; | |
// SANITIZE THE TIME | |
$time = str_replace(","," --> ", $time); | |
$time = str_replace(".",",", $time); | |
$srt .= $time . "\n"; | |
// GRAB TEXT | |
$text = $lines[$c + 2]; | |
// IF TWO LINES OF TEXT, APPEND IT | |
if( isset($lines[$c + 3]) AND $lines[$c + 3] != "") $text .= "\n" . $lines[$c + 3]; | |
// MUST ADD RETURNS TO END | |
$srt .= $text . "\n\n"; | |
// INCREMENT BLOCK NUMBER | |
$num++; | |
} | |
} | |
// RETURN THE GOODIES | |
return $srt; | |
} | |
// UPLOAD A SBV THROUGH A FORM | |
move_uploaded_file($_FILES['caption']['tmp_name'], "captions/{$id}.sbv"); | |
// GET THE CONTENTS OF THIS FILE | |
$sbv = file_get_contents("captions/{$id}.sbv"); | |
// CONVERT | |
$srt = convert_sbv_to_srt( $sbv ); | |
// WRITE BACK AS A .SRT | |
file_put_contents("captions/{$id}.srt", "\xEF\xBB\xBF" . htmlspecialchars_decode($srt, ENT_QUOTES)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks it works but leave PHP notice Undefined Offset on line 28 and 36;
I have fixed this here:
Fixed for warning file_get_contents: