Encode string to q encoding.
@link http://tools.ietf.org/html/rfc2047
@param string $str the text to encode
@param string $position Where the text is going to be used, see the RFC for what that means
@access public
@return string
498275
public function EncodeQ($str, $position = 'text') {
    //There should not be any EOL in the string
	$pattern="";
    $encoded = str_replace(array("\r", "\n"), '', $str);
    switch (strtolower($position)) {
      case 'phrase':
        $pattern = '^A-Za-z0-9!*+\/ -';
        break;

      case 'comment':
        $pattern = '\(\)"';
        //note that we dont break here!
        //for this reason we build the $pattern withoud including delimiters and []

      case 'text':
      default:
        //Replace every high ascii, control =, ? and _ characters
        //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
        $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
        break;
    }
    
    if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
      foreach (array_unique($matches[0]) as $char) {
        $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
      }
    }
    
    //Replace every spaces to _ (more readable than =20)
    return str_replace(' ', '_', $encoded);
}
824596
public static String decode(final String str) {
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Decodes str [" + str + "] failed", e);

            return str;
        }
    }
1099812
public function str_insert_i(string $insert, int $position): self
    {
        $insert = $this->inputConv($insert);
        $this->str = \substr_replace($this->str, $insert, $position << 2, 0);

        return $this;
    }
605541
private static function utf8ToHexSequence( $str ) {
		$buf = '';
		foreach ( preg_split( '//u', $str, -1, PREG_SPLIT_NO_EMPTY ) as $cp ) {
			$buf .= sprintf( '%04x ', self::utf8ToCodepoint( $cp ) );
		}

		return rtrim( $buf );
	}
1063659
public static String encode(String str)
	{
		try
		{
			return java.net.URLEncoder.encode(str, "UTF-8");
		}
		catch(java.io.UnsupportedEncodingException ue)
		{
			return str;
		}
	}
661421
private function strAdd(string $str, string $insertstr, int $pos):string
    {
        $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
        return $str;
    }
327836
private function charCodeAt($str, $index)
    {
        $char = mb_substr($str, $index, 1, 'UTF-8');
        if (mb_check_encoding($char, 'UTF-8')) {
            $ret = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');
            $result = hexdec(bin2hex($ret));

            return $result;
        }

        return;
    }
274837
public function substr($str, $offset = 0, $length = null)
    {
        return iconv_substr($str, $offset, $length, $this->getEncoding());
    }
923184
private static function _encodeQuotedPrintable($str)
    {
        $str = str_replace('=', '=3D', $str);
        $str = str_replace(self::$qpKeys, self::$qpReplaceValues, $str);
        $str = rtrim($str);
        return $str;
    }
1021009
public function writeString($str)
    {
        /**
         * This implementation supports only Basic Multilingual Plane
         * (BMP) characters (from 0x0000 to 0xFFFF) and doesn't support
         * "supplementary characters" (characters whose code points are
         * greater than 0xFFFF)
         * Java 2 represents these characters as a pair of char (16-bit)
         * values, the first from the high-surrogates range (0xD800-0xDBFF),
         * the second from the low-surrogates range (0xDC00-0xDFFF). Then
         * they are encoded as usual UTF-8 characters in six bytes.
         * Standard UTF-8 representation uses four bytes for supplementary
         * characters.
         */

        // convert input to a string before iterating string characters
        settype($str, 'string');

        $chars = $strlen = strlen($str);
        $containNullChars = false;

        for ($count = 0; $count < $strlen; $count++ ) {
            /**
             * String is already in Java 2 representation.
             * We should only calculate actual string length and replace
             * \x00 by \xC0\x80
             */
            if ((ord($str[$count]) & 0xC0) == 0xC0) {
                $addBytes = 1;
                if (ord($str[$count]) & 0x20 ) {
                    $addBytes++;

                    // Never used. Java2 doesn't encode strings in four bytes
                    // and we dont't support non-BMP characters
                    if (ord($str[$count]) & 0x10 ) {
                        $addBytes++;
                    }
                }
                $chars -= $addBytes;

                if (ord($str[$count]) == 0 ) {
                    $containNullChars = true;
                }
                $count += $addBytes;
            }
        }

        if ($chars < 0) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Invalid UTF-8 string');
        }

        $this->writeVInt($chars);
        if ($containNullChars) {
            $this->_fwrite(str_replace($str, "\x00", "\xC0\x80"));
        } else {
            $this->_fwrite($str);
        }
    }
684305
public static function altEncrypt($str, $pass = '')
    {
        /**
         * if empty values return null
         */
        if (!$str) {
            return null;
        }

        /**
         * ------------------------------------
         * Safe Sanitized hash
         * ------------------------------------
         */
        (is_null($pass) || $pass === false) && $pass = '';
        // safe is use array or object as hash
        $pass = Util::maybeSerialize($pass);
        if (!$pass) {
            $pass = sha1($pass);
        }

        // make an array values -> use key acb
        $str = serialize(array('acb' => $str));
        // rotate 13
        $str = pack('a*', Util::rotate($str.sha1(sha256::hash($pass)), 13));

        /**
         * Doing safe encode base 64
         */
        $str = Util::safeBase64Encode($str);

        /**
         * ------------------------------------
         * Doing convert string
         * ------------------------------------
         */
        $str_arr  = str_split($str);
        $add = 0;
        $div = strlen($str) / strlen($pass);
        $new_pass = '';
        while ($add <= $div) {
            $new_pass .= $pass;
            $add++;
        }
        $pass_arr = str_split($new_pass);
        $ascii = '';
        foreach ($str_arr as $key => $asc) {
            $pass_int = ord($pass_arr[$key]);
            $str_int = ord($asc);
            $int_add = $str_int + $pass_int;
            $ascii .= chr(($int_add+strlen($str)));
        }
        $ascii = trim(Util::safeBase64Encode($ascii));

        /**
         * ------------------------------------
         * Inject Result of with sign
         * ------------------------------------
         */
        if (strlen($ascii) > 10) {
            return substr_replace($ascii, '_aCb=', 10, 0);
        } else {
            return substr_replace($ascii, '_aCb=', 2, 0);
        }
    }
957120
function encode_qp ($str) {
      $encoded = $this->fix_eol($str);
      if (substr($encoded, -2) != "\r\n")
         $encoded .= "\r\n";

      // Replace every high ascii, control and = characters
      $encoded = preg_replace("/([\001-\010\013\014\016-\037\075\177-\377])/e",
                 "'='.sprintf('%02X', ord('\\1'))", $encoded);
      // Replace every spaces and tabs when it's the last character on a line
      $encoded = preg_replace("/([\011\040])\r\n/e",
                 "'='.sprintf('%02X', ord('\\1')).'\r\n'", $encoded);

      // Maximum line length of 76 characters before CRLF (74 + space + '=')
      $encoded = $this->WordWrap($encoded, 74, true);

      return $encoded;
   }
81816
private String encodeString(String str) {
        m_buffer.setLength(0);
        char ch;
        int inx = 0;
        while (inx < str.length()) {
            ch = str.charAt(inx++);
            switch (ch) {
            case '"':  m_buffer.append("\\\""); break;
            case '\\': m_buffer.append("\\\\"); break;
            case '\b':  m_buffer.append("\\b"); break;
            case '\f':  m_buffer.append("\\f"); break;
            case '\n':  m_buffer.append("\\n"); break;
            case '\r':  m_buffer.append("\\r"); break;
            case '\t':  m_buffer.append("\\t"); break;
            default:
                // All other chars are allowed as-is, despite JSON spec.
                m_buffer.append(ch);
            }
        }
        return m_buffer.toString();
    }
1276369
function utf8_byte2char_pos($str, $pos) {
		$n = 0; // number of characters
		for ($i = $pos; $i > 0; $i--) {
			$c = (int) ord($str{$i});
			if (!($c & 0x80)) // single-byte (0xxxxxx)
			{
				$n++;
			}
			elseif (($c & 0xC0) == 0xC0) // multi-byte starting byte (11xxxxxx)
			{
				$n++;
			}
		}
		if (!strlen($str{$i})) {
			return FALSE;
		} // offset beyond string length

		return $n;
	}
503587
function decode(str) {
  let off = 0;
  let olen = 0;
  const slen = str.length;
  const stra = [];
  const len = str.length;

  while (off < slen - 1 && olen < len) {
    let code = str.charCodeAt(off++);
    const c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    code = str.charCodeAt(off++);
    const c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    if (c1 === -1 || c2 === -1) break;
    let o = (c1 << 2) >>> 0;
    o |= (c2 & 0x30) >> 4;
    stra.push(String.fromCharCode(o));
    if (++olen >= len || off >= slen) break;
    code = str.charCodeAt(off++);
    const c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    if (c3 === -1) break;
    o = ((c2 & 0x0f) << 4) >>> 0;
    o |= (c3 & 0x3c) >> 2;
    stra.push(String.fromCharCode(o));
    if (++olen >= len || off >= slen) break;
    code = str.charCodeAt(off++);
    const c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
    o = ((c3 & 0x03) << 6) >>> 0;
    o |= c4;
    stra.push(String.fromCharCode(o));
    ++olen;
  }
  const buffa = [];
  for (off = 0; off < olen; off++) buffa.push(stra[off].charCodeAt(0));
  return Buffer.from(buffa);
}
80405
public static function toUTF8($str)
    {
        if (!is_null($str) && false === mb_detect_encoding($str, 'UTF-8', true)) {
            $str = utf8_encode($str);
        }

        return $str;
    }
606978
public function getCharAt( $position )
	{
		if($position <= $this->count() && $position >= 0 )
			$character = $this->buffer[$position];
		return $character;
	}