The InputStream reads a single byte at a time, and it considers \r to be a regular token.
When Parser::detectSymbols() encounters a \r token, it throws a "invalid character" exception.
The simplest fix would be to normalize line endings before to normalize whitespace before tokenizing, like
$term = preg_replace('/\s+/', ' ', $term);