<?php
$srt = <<<SRT
1
00:00:12,759 --> 00:00:17,458
"some content here "
that continues here
2
00:00:18,298 --> 00:00:20,926
here we go again...
3
00:00:21,368 --> 00:00:24,565
...and this can go forever...
SRT;
$lines = explode("\r\n", $srt); // simulate file()
class SRTBlocks implements Iterator
{
private $lines;
private $current;
private $key;
public function __construct($lines)
{
if (is_array($lines))
{
$lines = new ArrayIterator($lines);
}
$this->lines = $lines;
}
public function rewind()
{
$this->lines->rewind();
$this->current = NULL;
$this->key = 0;
}
public function valid()
{
return $this->lines->valid();
}
public function current()
{
if (NULL !== $this->current)
{
return $this->current;
}
$state = 0;
$block = NULL;
while ($this->lines->valid() && $line = $this->lines->current())
{
switch($state)
{
case 0:
$block = array();
$block['number'] = $line;
$state = 1;
break;
case 1:
$block['range'] = $line;
$state = 2;
break;
case 2:
$block['text'] = '';
$state = 3;
# fall-through intended
case 3:
if ($line === '') {
$state = 0;
break 2;
}
$block['text'] .= ($block['text'] ? "\n" : '') . $line;
break;
default:
throw new Exception(sprintf('Unhandled %d.', $state));
}
$this->lines->next();
}
if (NULL === $block)
{
throw new Exception('Parser invalid (empty).');
}
$this->current = $block;
$this->key++;
return $block;
}
public function key()
{
return $this->key;
}
public function next()
{
$this->lines->next();
$this->current = NULL;
}
}
$blocks = new SRTBlocks($lines);
foreach($blocks as $index => $block)
{
printf("Block #%d:\n", $index);
print_r($block);
}