public static function escapeBinary($string)
    {
        $escaped = '';

        for ($i = 0; $i < mb_strlen($string, '8bit'); $i++) {
            $char = mb_substr($string, $i, 1, '8bit');
            $ord = ord($char);
            if ($ord === 9) {
                $escaped .= '\t';
            } elseif ($ord === 10) {
                $escaped .= '\n';
            } elseif ($ord === 13) {
                $escaped .= '\r';
            } elseif ($ord === 92) {
                $escaped .= '\\\\';
            } elseif ($ord < 16) {
                $escaped .= '\x0' . mb_strtoupper(dechex($ord));
            } elseif ($ord < 32 || $ord >= 127) {
                $escaped .= '\x' . mb_strtoupper(dechex($ord));
            } else {
                $escaped .= $char;
            }
        }

        return $escaped;
    }