I tried two approaches, but I can't quite get it.
Approach 1 involved writing using cursor control. I think technically this would be using the output buffer? Sadly, I can't get it to work because each time I do a left cursor, I don't insert the next char, i just overwrite the char that was to the left:
function read()
{
static $string = 'This is a test; it is only a test; it is not the real thing; if it were the real thing you would not be reading this; you would be reading something else.';
static $position = 0;
return $string[$position++];
}
function move_end() {
echo chr(3);
}
$reverse = false;
$cursor = 0;
while (true) {
$c = read();
if ($c == '.') {
// current word finished, go to end
move_end();
echo $c;
// output finished
break;
} elseif ($c == ' ') {
// current word finished, go to end
move_end();
echo $c;
} elseif ($c == ';') {
// current word finished, go to end
move_end();
echo $c;
// flip reversing
$reverse = !$reverse;
} else {
// some word character. append to word
if ($reverse) {
// cursor left
echo "\033[D";
}
echo $c;
}
}
echo "\n";
The output:
This is a test;tsyat; it is not the real thing;fteelgudtegs; you would be reading something else.
Approach 2 I tried recursion but I can't quite get my head around it:
function read()
{
static $string = 'This is a test; it is only a test; it is not the real thing; if it were the real thing you would not be reading this; you would be reading something else.';
static $position = 0;
return $string[$position++];
}
$reverse = false;
function echo_next() {
global $reverse;
$c = read();
if (!in_array($c, ['.', ';'])) {
// some word character. append to word
if ($reverse && $c != ' ') {
echo_next();
}
echo $c;
} elseif ($c == '.') {
echo $c;
// output finished
throw new Exception('output finished');
} elseif ($c == ';') {
echo $c;
$reverse = !$reverse;
}
}
while (true) {
try {
echo_next();
} catch (Exception $e) {
break;
}
}
echo "\n";
The output:
This is a test; ti si ylno a;tset it is not the real thing; fi ti erew eht laer gniht uoy dluow ton eb gnidaer;siht you would be reading something else.
You'll note it doubles up the spaces and wrongly reverses the first word sometimes. I give up. This hurts my brain.