Skip to content

Instantly share code, notes, and snippets.

@annedorko
Created March 23, 2017 18:18
Show Gist options
  • Save annedorko/501d9cc4885e8ea8f39a9c57fd49ebc6 to your computer and use it in GitHub Desktop.
Save annedorko/501d9cc4885e8ea8f39a9c57fd49ebc6 to your computer and use it in GitHub Desktop.
Turn copy & paste Facebook video captions into a .SRT file
<?php
/**
* Facebook Video Caption Editor Copy & Paste to SRT
*
* Original script by Anne Dorko
*
* Why? I tried adding custom Facebook captions to my live video,
* and it wouldn't save. 45 minutes of my life wasted! But wait...
* I copied and pasted the timestamps and subtitles into a plain
* text file and then processed it to create an .SRT
*
* General usage:
* Copy and paste your failed Facebook captions straight from the GUI
* Save it as a plain text file next to this one called subtitles.txt
* Open this script in a browser.
*/
/*
The expected textfile for subtitles should have content like this:
00:02.730
00:03.590
Good morning
00:04.060
00:06.920
It's about 10am on Thursday for me and I have been
00:06.930
00:09.740
wanting to talk about dictionaries and why I
*/
$file_name = 'subtitles.txt';
$file = file( $file_name );
/*
$count lets us track in, out, and subtitle text as sets of three
*/
$count = 0;
/*
$set gives us keys starting at 1 to use in the output per line
*/
$set = 1;
$data = array();
foreach( $file as $line ) {
// Get rid of extra spaces
$line = trim( $line );
// Ignore empty lines!
if ( empty( $line ) ) { continue; }
// Track sets of three
$count++;
if ( $count > 3 ) {
$count = 1;
$set++;
}
// The first and second in every set are the time in/out timestamps
if ( $count == 1 ) {
$data[$set]['time_in'] = replace_last_period_with_comma( $line );
}
if ( $count == 2 ) {
$data[$set]['time_out'] = replace_last_period_with_comma( $line );
}
// The final in every set is the subtitle text
if ( $count == 3 ) {
$data[$set]['text'] = $line;
}
}
/*
Name your subtitles whatever you like. Set en_US to the correct language format for your subtitles.
*/
$create_file = fopen( 'subtitles.en_US.srt', 'w' );
$key = 1;
foreach ( $data as $title ) {
// This is the correct SRT formatting
extract( $title );
$subtitle = "$key\n$time_in --> $time_out\n$text\n\n";
fwrite( $create_file, $subtitle );
$key++;
}
// Save file
fclose( $create_file );
echo '<a href="subtitles.en_US.srt">Right-click and save this file to upload to Facebook.</a>';
/**
* replace_last_period_with_comma Facebook displays time values wrong for SRT files if you simply copy and paste from the GUI, this function corrects that.
* @param string $string The time value given from Facebook
* @return string Returns an SRT standard time format
*/
function replace_last_period_with_comma( $string ) {
$pos = strrpos( $string, '.' );
if ( false !== $pos ) {
$string = substr_replace( $string, ',', $pos, 1 );
}
return '00:' . $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment