Encode a string in requested format.
Returns an empty string on failure.

@param string $str      The text to encode
@param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'

@return string
541856
public function encodeString($str, $encoding = self::ENCODING_BASE64)
    {
        $encoded = '';
        switch (strtolower($encoding)) {
            case static::ENCODING_BASE64:
                $encoded = chunk_split(
                    base64_encode($str),
                    static::STD_LINE_LENGTH,
                    static::$LE
                );
                break;
            case static::ENCODING_7BIT:
            case static::ENCODING_8BIT:
                $encoded = static::normalizeBreaks($str);
                // Make sure it ends with a line break
                if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
                    $encoded .= static::$LE;
                }
                break;
            case static::ENCODING_BINARY:
                $encoded = $str;
                break;
            case static::ENCODING_QUOTED_PRINTABLE:
                $encoded = $this->encodeQP($str);
                break;
            default:
                $this->setError($this->lang('encoding') . $encoding);
                break;
        }

        return $encoded;
    }
1097103
public static function alphanumeric(string $str, string $encoding = null) : bool
    {
        return static::matchesPattern($str, '^[[:alnum:]]*$', $encoding);
    }
807350
public static function Utf7ImapToUtf8($str)
    {
        if ($str instanceof Horde_Imap_Client_Mailbox) {
            return $str->utf8;
        }

        $str = strval($str);

        /* Try mbstring, if available, which should be faster. Don't use the
         * IMAP utf7_* functions because they are known to be buggy. */
        if (is_null(self::$_mbstring)) {
            self::$_mbstring = extension_loaded('mbstring');
        }
        if (self::$_mbstring) {
            return @mb_convert_encoding($str, 'UTF-8', 'UTF7-IMAP');
        }

        $p = '';
        $ptr = &self::$_index64;

        for ($i = 0, $u7len = strlen($str); $u7len > 0; ++$i, --$u7len) {
            $u7 = $str[$i];
            if ($u7 === '&') {
                $u7 = $str[++$i];
                if (--$u7len && ($u7 === '-')) {
                    $p .= '&';
                    continue;
                }

                $ch = 0;
                $k = 10;
                for (; $u7len > 0; ++$i, --$u7len) {
                    $u7 = $str[$i];

                    if ((ord($u7) & 0x80) || ($b = $ptr[ord($u7)]) === -1) {
                        break;
                    }

                    if ($k > 0) {
                        $ch |= $b << $k;
                        $k -= 6;
                    } else {
                        $ch |= $b >> (-$k);
                        if ($ch < 0x80) {
                            /* Printable US-ASCII */
                            if ((0x20 <= $ch) && ($ch < 0x7f)) {
                                throw new Horde_Imap_Client_Exception(
                                    Horde_Imap_Client_Translation::r("Error converting UTF7-IMAP string."),
                                    Horde_Imap_Client_Exception::UTF7IMAP_CONVERSION
                                );
                            }
                            $p .= chr($ch);
                        } else if ($ch < 0x800) {
                            $p .= chr(0xc0 | ($ch >> 6)) .
                                  chr(0x80 | ($ch & 0x3f));
                        } else {
                            $p .= chr(0xe0 | ($ch >> 12)) .
                                  chr(0x80 | (($ch >> 6) & 0x3f)) .
                                  chr(0x80 | ($ch & 0x3f));
                        }

                        $ch = ($b << (16 + $k)) & 0xffff;
                        $k += 10;
                    }
                }

                /* Non-zero or too many extra bits -OR-
                 * Base64 not properly terminated -OR-
                 * Adjacent Base64 sections. */
                if (($ch || ($k < 6)) ||
                    (!$u7len || $u7 !== '-') ||
                    (($u7len > 2) &&
                     ($str[$i + 1] === '&') &&
                     ($str[$i + 2] !== '-'))) {
                    throw new Horde_Imap_Client_Exception(
                        Horde_Imap_Client_Translation::r("Error converting UTF7-IMAP string."),
                        Horde_Imap_Client_Exception::UTF7IMAP_CONVERSION
                    );
                }
            } elseif ((ord($u7) < 0x20) || (ord($u7) >= 0x7f)) {
                /* Not printable US-ASCII */
                throw new Horde_Imap_Client_Exception(
                    Horde_Imap_Client_Translation::r("Error converting UTF7-IMAP string."),
                    Horde_Imap_Client_Exception::UTF7IMAP_CONVERSION
                );
            } else {
                $p .= $u7;
            }
        }

        return $p;
    }
1178854
public static function toUpperCase($str, $encoding = null)
    {
        return (string) Stringy::create($str, $encoding)->toUpperCase();
    }
38012
public static function humanize($str, $encoding = null)
    {
        return (string) Stringy::create($str, $encoding)->humanize();
    }
374891
function utf8_to_entities($str) {
		$strLen = strlen($str);
		$outStr = '';
		$buf = '';
		for ($a = 0; $a < $strLen; $a++) { // Traverse each char in UTF-8 string.
			$chr = substr($str, $a, 1);
			$ord = ord($chr);
			if ($ord > 127) { // This means multibyte! (first byte!)
				if ($ord & 64) { // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
					$buf = $chr; // Add first byte
					for ($b = 0; $b < 8; $b++) { // for each byte in multibyte string...
						$ord = $ord << 1; // Shift it left and ...
						if ($ord & 128) { // ... and with 8th bit - if that is set, then there are still bytes in sequence.
							$a++; // Increase pointer...
							$buf .= substr($str, $a, 1); // ... and add the next char.
						} else {
							break;
						}
					}

					$outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
				} else {
					$outStr .= chr($this->noCharByteVal);
				} // No char exists (MIDDLE of MB sequence!)
			} else {
				$outStr .= $chr;
			} // ... otherwise it's just ASCII 0-127 and one byte. Transparent
		}

		return $outStr;
	}
301079
public static function upperFirst(string $str, string $encoding = null) : string
    {
        $encoding = $encoding ?: utils\Str::encoding($str);

        // Uppercase the first character and append the remainder.
        return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr($str, 1, null, $encoding);
    }
966248
function utf8_encode($str, $charset) {

		if ($charset === 'utf-8') {
			return $str;
		}

			// Charset is case-insensitive.
		if ($this->initCharset($charset)) { // Parse conv. table if not already...
			$strLen = strlen($str);
			$outStr = '';

			for ($a = 0; $a < $strLen; $a++) { // Traverse each char in string.
				$chr = substr($str, $a, 1);
				$ord = ord($chr);
				if (isset($this->twoByteSets[$charset])) { // If the charset has two bytes per char
					$ord2 = ord($str{$a + 1});
					$ord = $ord << 8 | $ord2; // assume big endian

					if (isset($this->parsedCharsets[$charset]['local'][$ord])) { // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
						$outStr .= $this->parsedCharsets[$charset]['local'][$ord];
					} else {
						$outStr .= chr($this->noCharByteVal);
					} // No char exists
					$a++;
				} elseif ($ord > 127) { // If char has value over 127 it's a multibyte char in UTF-8
					if (isset($this->eucBasedSets[$charset])) { // EUC uses two-bytes above 127; we get both and advance pointer and make $ord a 16bit int.
						if ($charset != 'shift_jis' || ($ord < 0xA0 || $ord > 0xDF)) { // Shift-JIS: chars between 160 and 223 are single byte
							$a++;
							$ord2 = ord(substr($str, $a, 1));
							$ord = $ord * 256 + $ord2;
						}
					}

					if (isset($this->parsedCharsets[$charset]['local'][$ord])) { // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
						$outStr .= $this->parsedCharsets[$charset]['local'][$ord];
					} else {
						$outStr .= chr($this->noCharByteVal);
					} // No char exists
				} else {
					$outStr .= $chr;
				} // ... otherwise it's just ASCII 0-127 and one byte. Transparent
			}
			return $outStr;
		}
	}
1320007
public function str2bin(string $str):string {
		$chrs = unpack('C*', $str);

		return vsprintf(str_repeat('%08b', count($chrs)), $chrs);
	}
1196126
public static function strlen($str, $encoding = 'UTF-8') {
	    if(function_exists('iconv_strlen')) {
	        return iconv_strlen($str, $encoding);
	    } elseif(function_exists('mb_strlen')) {
	        return mb_strlen($str, $encoding);
	    }
	    throw new \Exception('请先安装PHP iconv或mb_string扩展');
	}
783865
public function ucfirst($str, $encoding = null)
	{
		$encoding or $encoding = $this->encoding;

		return function_exists('mb_strtoupper')
			? mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding).
				mb_substr($str, 1, mb_strlen($str, $encoding), $encoding)
			: ucfirst($str);
	}
280830
public static function encodingWithUtf8($str)
    {
        $cur_encoding = mb_detect_encoding($str);
        if ($cur_encoding == "UTF-8" && mb_check_encoding($str, "UTF-8")) {
            return $str;
        } else {
            return utf8_encode($str);
        }
    }
670280
public static function reverse(string $str, string $encoding = null) : string
    {
        $encoding = $encoding ?: static::encoding($str);
        $length   = mb_strlen($str, $encoding);
        $result   = '';

        // Return early under obvious circumstances.
        if ($length === 0) {
            return $result;
        }

        // Reverse one character after the other, counting from the end.
        for ($i = $length - 1; $i >= 0; $i--) {
            $result .= mb_substr($str, $i, 1, $encoding);
        }

        return $result;
    }
661090
public static function convertEncoding( $str, $to_encoding = NULL, $from_encoding = NULL )
    {
        if ( is_string($str) && $to_encoding ){
            // エンコードあり
            return mb_convert_encoding($str,$to_encoding, $from_encoding);
        }
        // エンコード無し
        return $str;
    }
531169
private String encode(String str) {
        if (str == null) {
            return null;
        }
        try {
            return URLEncoder.encode(str, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            // Should never happen
            throw Throwables.propagate(e);
        }
    }
116556
public function mbStrLen($string, $encoding = null)
    {
        // Meh, the original mb_strlen interprets a null here as an empty string.
        if ($encoding === null) {
            return mb_strlen($string);
        }
        return mb_strlen($string, $encoding);
    }
199318
public static function encode(String $str) : String
    {
        return str_replace(array_keys(self::$phpTagChars), array_values(self::$phpTagChars), $str);
    }