I'm not sure I correctly understand all the constraints, but I couldn't think of any way to do this without accumulating words in a var.
<?php
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++];
}
$word = '';
$reverse = false;
$output = '';
while (true) {
$c = read();
// echo $c;
if ($c == '.') {
// current word finished
$output .= $word;
$word = '';
// add c to output
$output .= $c;
// output finished
break;
} elseif ($c == ' ') {
// current word finished, append it
$output .= $word;
$word = '';
// add c to output
$output .= $c;
} elseif ($c == ';') {
// current word finished, append it
$output .= $word;
$word = '';
// add c to output
$output .= $c;
// flip reversing
$reverse = !$reverse;
} else {
// some word character. append to word
if ($reverse) {
$word = $c . $word;
} else {
$word = $word . $c;
}
}
}
echo $output;
echo "\n";
Please let me know if I've violated anything. I could probably eliminate my $output var, but I can't think of any way to eliminate my $word var.