Change a string from one encoding to another

@param string $data Raw data in $input encoding
@param string $input Encoding of $data
@param string $output Encoding you want
@return string|boolean False if we can't convert it
421042
public static function change_encoding($data, $input, $output)
	{
		$input = SimplePie_Misc::encoding($input);
		$output = SimplePie_Misc::encoding($output);

		// We fail to fail on non US-ASCII bytes
		if ($input === 'US-ASCII')
		{
			static $non_ascii_octects = '';
			if (!$non_ascii_octects)
			{
				for ($i = 0x80; $i <= 0xFF; $i++)
				{
					$non_ascii_octects .= chr($i);
				}
			}
			$data = substr($data, 0, strcspn($data, $non_ascii_octects));
		}

		// This is first, as behaviour of this is completely predictable
		if ($input === 'windows-1252' && $output === 'UTF-8')
		{
			return SimplePie_Misc::windows_1252_to_utf8($data);
		}
		// This is second, as behaviour of this varies only with PHP version (the middle part of this expression checks the encoding is supported).
		elseif (function_exists('mb_convert_encoding') && ($return = SimplePie_Misc::change_encoding_mbstring($data, $input, $output)))
		{
			return $return;
 		}
		// This is third, as behaviour of this varies with OS userland and PHP version
		elseif (function_exists('iconv') && ($return = SimplePie_Misc::change_encoding_iconv($data, $input, $output)))
		{
			return $return;
		}
		// This is last, as behaviour of this varies with OS userland and PHP version
		elseif (class_exists('\UConverter') && ($return = SimplePie_Misc::change_encoding_uconverter($data, $input, $output)))
		{
			return $return;
		}
		// If we can't do anything, just fail
		else
		{
			return false;
		}
	}
292090
public static function utf8Encode($data) {
		if (is_string($data)) {
			return utf8_encode($data);

		} else if (is_array($data)) {
			foreach ($data as $key => $value) {
				$data[utf8_encode($key)] = self::utf8Encode($value);
			}

		} else if (is_object($data)) {
			foreach ($data as $key => $value) {
				$data->{$key} = self::utf8Encode($value);
			}
		}

		return $data;
	}
1124098
public static function unescap($data, $type = 0, $encoding = 'UTF-8')
    {
        if (\is_array($data)) {

            foreach ($data as $k => $v) {
                $data[$k] = self::unescap($data, $type, $encoding);
            }

        } else {
            if (!$type) {//默认使用  htmlspecialchars_decode()
                $data = htmlspecialchars_decode($data, ENT_QUOTES);
            } else {
                $data = html_entity_decode($data, ENT_QUOTES, $encoding);
            }

        }

        return $data;
    }
585701
public function setInput($data, $encoding = '')
    {
        $this->_input    = $data;
        $this->_encoding = $encoding;
        $this->reset();
    }
790864
private function initType($data)
    {
        if (!is_string($data)) return false;

        $data = trim($data);
        switch (true) {
            case (in_array($data, ['true', 'false'])):
                $this->data = (bool)(strpos($data, 'true') !== false) ? true : false;
                break;
            case !is_numeric($data):
                if ($res = json_decode($data)) {
                    $this->data = $res;
                } else if (($res = @unserialize($data)) !== false) {
                    $this->data = $res;
                } else if ((preg_match('/^["|\']{1}(.*)["|\']{1}$/', $data, $match)) === 1) {
                    $this->data = (string)$match[1];
                } else {
                    $this->data = (string)$data;
                }
                break;

            default:
                // integer
                if (is_numeric($data) && strpos($data, '.') === false) {
                    $this->data = (int)$data;
                } else {
                    $this->data = (float)$data;
                }
                break;
        }

        return true;
    }
86548
protected function encode($data)
    {
        switch ($this->responseEncoding){
            case "application/rdf+xml":
                throw new common_exception_NotImplemented();
                break;
            case "text/xml":
            case "application/xml":
                return tao_helpers_Xml::from_array($data);
            case "application/json":
            default:
                return json_encode($data);
        }
    }
1326273
public static function convertToUtf8($data, $encoding) {
    if (function_exists('iconv')) {
      return @iconv($encoding, 'utf-8', $data);
    }
    elseif (function_exists('mb_convert_encoding')) {
      return @mb_convert_encoding($data, 'utf-8', $encoding);
    }
    elseif (function_exists('recode_string')) {
      return @recode_string($encoding . '..utf-8', $data);
    }
    // Cannot convert.
    return FALSE;
  }
395571
public function replace( $string, $data ) {
		foreach ( $data as $k => $v ) {
			$string = str_replace( '${' . $k . '}', $v, $string );
		}

		return $string;
	}
1030478
function encodeSubject($input, $charset = 'ISO-8859-1')
  {
    // set the internal encoding to the encoding of the given input
    // this way no conversion is done, because we only need the 'Q' encoding
    $old_enc=mb_internal_encoding();
    mb_internal_encoding($charset);
    $output=mb_encode_mimeheader($input,$charset, 'Q', $this->LE);
    // and when ready, restore the internal encoding again
    mb_internal_encoding($old_enc);
    return $output;
    // below is a fallback mechanism which seems to work also
    /*
    preg_match_all('/(\\w*[\\x80-\\xFF]+\\w*)/', $input, $matches);
    foreach ($matches[1] as $value) {
      $replacement = preg_replace('/([\\x80-\\xFF])/e', '"=" . strtoupper(dechex(ord("\\1")))', $value);
      $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
    }
    return $input;
    */
  }
974664
public static function idn_convert($input, $is_utf = false)
    {
        if ($at = strpos($input, '@')) {
            $user   = substr($input, 0, $at);
            $domain = substr($input, $at + 1);
        }
        else {
            $user   = '';
            $domain = $input;
        }

        // Note that in PHP 7.2/7.3 calling idn_to_* functions with default arguments
        // throws a warning, so we have to set the variant explicitely (#6075)
        $variant = defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : null;
        $options = 0;

        // Because php-intl extension lowercases domains and return false
        // on invalid input (#6224), we skip conversion when not needed
        // for compatibility with our Net_IDNA2 wrappers in bootstrap.php

        if ($is_utf) {
            if (preg_match('/[^\x20-\x7E]/', $domain)) {
                $domain = idn_to_ascii($domain, $options, $variant);
            }
        }
        else if (preg_match('/(^|\.)xn--/i', $domain)) {
            $domain = idn_to_utf8($domain, $options, $variant);
        }

        if ($domain === false) {
            return '';
        }

        return $at ? $user . '@' . $domain : $domain;
    }
32494
private function safe_encode($data) {
    if (is_array($data)) {
      return array_map(array($this, 'safe_encode'), $data);
    } else if (is_scalar($data)) {
      return str_ireplace(
        array('+', '%7E'),
        array(' ', '~'),
        rawurlencode($data)
      );
    } else {
      return '';
    }
  }
473411
public static function encode($input, $serialized = false)
    {
        // use Base64 encoding to workaround issues with invalid
        // or null characters in serialized string (#1489142)
        if ($serialized) {
            return base64_encode(serialize($input));
        }

        if (is_object($input)) {
            foreach (get_object_vars($input) as $idx => $value) {
                $input->$idx = self::encode($value);
            }
            return $input;
        }
        else if (is_array($input)) {
            foreach ($input as $idx => $value) {
                $input[$idx] = self::encode($value);
            }

            return $input;
        }

        return utf8_encode($input);
    }
385527
public function characet($data, $targetCharset) {

		if (!empty($data)) {
			$fileType = 'UTF-8';
			if (strcasecmp($fileType, $targetCharset) != 0) {
				$data = mb_convert_encoding($data, $targetCharset, $fileType);
				//				$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
			}
		}

		return $data;
	}
754763
public static String replaceDataReferencesInString(final String input, final Map<String, Map<String, String>> data) {
        return replaceDataReferencesInString(input, data, null, false);
    }
754169
public function encode($data)
    {

        // Convert the data to a binary string.
        $bits = '';
        foreach (str_split($data) as $char) {
            $bits .= sprintf('%08b', ord($char));
        }

        // Make sure the string length is a multiple of 5, padding if needed.
        $len = strlen($bits);
        $mod = $len % 5;
        if ($mod !== 0) {
            $bits = str_pad($bits, $len + 5 - $mod, '0', STR_PAD_RIGHT);
        }

        // Split the binary string into 5-bit chunks and encode each chunk.
        $output = '';
        foreach (str_split($bits, 5) as $chunk) {
            $output .= substr($this->getConfig('alphabet'), bindec($chunk), 1);
        }

        return $output;

    }
113523
public function encodeUtf8($data)
    {
        if ($data === null || $data === '') {
            return $data;
        }
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $data[$key] = $this->encodeUtf8($value);
            }

            return $data;
        } else {
            if (!mb_check_encoding($data, 'UTF-8')) {
                return mb_convert_encoding($data, 'UTF-8');
            }

            return $data;
        }
    }
595057
public static function changeEncode($data, $in_charset = 'GBK', $out_charset = 'UTF-8')
    {
        if (\is_array($data)) {

            foreach ($data as $key => $value) {
                $data[$key] = self::changeEncode($value, $in_charset, $out_charset);
            }

            return $data;
        }

        if (\function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($data, $out_charset, $in_charset);
        }

        return iconv($in_charset, $out_charset . '/' . '/IGNORE', $data);
    }