Skip to content

Instantly share code, notes, and snippets.

@halgatewood
Last active February 22, 2020 15:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halgatewood/0dbad64e6404c582e9b01eeb946ed3ae to your computer and use it in GitHub Desktop.
Save halgatewood/0dbad64e6404c582e9b01eeb946ed3ae to your computer and use it in GitHub Desktop.
PHP Function to Convert SBV to SRT
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));
@aalfiann
Copy link

aalfiann commented Jan 9, 2018

Thanks it works but leave PHP notice Undefined Offset on line 28 and 36;

I have fixed this here:

if (!empty($lines[$c + 1])){
    			// GRAB THE TIME 
	    		$time = $lines[$c + 1];

                // SANITIZE THE TIME
			    $time = str_replace(","," --> ", $time);
    			$time = str_replace(".",",", $time);
	    		$srt .= $time . "\n";
            }	
            
            if (!empty($lines[$c + 2])){
    			// 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";
            }

Fixed for warning file_get_contents:

// GET THE CONTENTS OF THIS FILE
$sbv  = @file_get_contents("captions/{$id}.sbv");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment