[ create a new paste ] login | about

Link: http://codepad.org/0hH17LVV    [ raw code | output | fork ]

PHP, pasted on Dec 23:
<?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);
}


Output:
Block #1:
Array
(
    [number] => 1
    [range] => 00:00:12,759 --> 00:00:17,458
    [text] => "some content here "
that continues here
)
Block #2:
Array
(
    [number] => 2
    [range] => 00:00:18,298 --> 00:00:20,926
    [text] => here we go again...
)
Block #3:
Array
(
    [number] => 3
    [range] => 00:00:21,368 --> 00:00:24,565
    [text] => ...and this can go forever...
)


Create a new paste based on this one


Comments: