Replaced substr($str, 0, -1) with unpack('A*', $str) which removes any trailing whitespace and works nicely if there is not whitespace at the end.