https://github.com/nette/nette/blob/master/Nette/Utils/Strings.php#L188
Converts to web safe characters [a-z0-9-] text.
@param  string  UTF-8 encoding
@param  string  allowed characters
@param  bool
@return string
335049
public static function webalize($s, $charlist = null, $lower = true)
    {
        $s = self::toAscii($s);
        if ($lower) {
            $s = strtolower($s);
        }
        $s = preg_replace('#[^a-z0-9' . preg_quote($charlist, '#') . ']+#i', '_', $s);
        $s = trim($s, '_');
        return $s;
    }
799809
private static function bool2str($v) {
        //convert boolean to text value.
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        return $v;
    }
951407
public static function unicode_to_utf8( &$str )
    {
        if (!is_array($str)) return '';

        $utf8 = '';
        foreach( $str as $unicode ) {
            if ( $unicode < 128 ) {
                $utf8.= chr( $unicode );
            } elseif ( $unicode < 2048 ) {
                $utf8.= chr( 192 +  ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
                $utf8.= chr( 128 + ( $unicode % 64 ) );
            } else {
                $utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
                $utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
                $utf8.= chr( 128 + ( $unicode % 64 ) );
            }
        }
        return $utf8;
    }
123092
public function convert_to_utf8($str, $encoding)
    {
        if (MB_ENABLED) {
            return mb_convert_encoding($str, 'UTF-8', $encoding);
        } elseif (ICONV_ENABLED) {
            return @iconv($encoding, 'UTF-8', $str);
        }

        return FALSE;
    }
462627
private static Integer legalCharacter(final Opt<Integer> data,
        final ByteArrayOutputStream baos, final Integer position)
        throws HttpException {
        // @checkstyle MagicNumber (1 line)
        if ((data.get() > 0x7f || data.get() < 0x20)
            && data.get() != '\t') {
            throw new HttpException(
                HttpURLConnection.HTTP_BAD_REQUEST,
                String.format(
                    "illegal character 0x%02X in HTTP header line #%d: \"%s\"",
                    data.get(),
                    position,
                    new Utf8String(baos.toByteArray()).asString()
                )
            );
        }
        return data.get();
    }
582621
static function iconv_fallback_iso88591_utf8($string, $bom=false) {
		if (function_exists('utf8_encode')) {
			return utf8_encode($string);
		}
		// utf8_encode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
		$newcharstring = '';
		if ($bom) {
			$newcharstring .= "\xEF\xBB\xBF";
		}
		for ($i = 0; $i < strlen($string); $i++) {
			$charval = ord($string{$i});
			$newcharstring .= getid3_lib::iconv_fallback_int_utf8($charval);
		}
		return $newcharstring;
	}
112922
public static function convertToUTF8($str)
    {
        $encoding = mb_detect_encoding($str, ['UTF-8', 'ISO-8859-1', 'WINDOWS-1252'], true);

        switch ($encoding) {
            case 'ISO-8859-1':
                $newStr = utf8_encode($str);
                break;
            /* Unreachable code. Not sure yet how we can improve this
             * situation.
            case 'WINDOWS-1252' :
                $newStr = iconv('cp1252', 'UTF-8', $str);
                break;
             */
            default:
                 $newStr = $str;
        }

        // Removing any control characters
        return preg_replace('%(?:[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F])%', '', $newStr);
    }
198158
public static function convertToUtf8(string $string): string
    {
        // If it's already a UTF8 string, just clean and return it
        if (static::isUtf8($string)) {
            return HtmlPurifier::cleanUtf8($string);
        }

        // Otherwise set HTMLPurifier to the actual string encoding
        $config = \HTMLPurifier_Config::createDefault();
        $config->set('Core.Encoding', static::encoding($string));

        // Clean it
        $string = HtmlPurifier::cleanUtf8($string);

        // Convert it to UTF8 if possible
        if (function_exists('iconv') && \HTMLPurifier_Encoder::testIconvTruncateBug() === \HTMLPurifier_Encoder::ICONV_OK) {
            $string = HtmlPurifier::convertToUtf8($string, $config);
        } else {
            $encoding = static::encoding($string);
            $string = mb_convert_encoding($string, 'utf-8', $encoding);
        }

        return $string;
    }
701517
private static int utf8Length(String string) {
    int stringLength = string.length();
    int utf8Length = 0;
    for (int i = 0; i < stringLength; i++) {
      int c = string.charAt(i);
      if (c <= 0x007F) {
        utf8Length++;
      } else if (c > 0x07FF) {
        utf8Length += 3;
      } else {
        utf8Length += 2;
      }
    }
    return utf8Length;
  }
281758
public static function utf8ord($utf8char) {
        if ($utf8char == '') {
            return 0;
        }
        $ord0 = ord($utf8char{0});
        if ($ord0 >= 0 && $ord0 <= 127) {
            return $ord0;
        }
        $ord1 = ord($utf8char{1});
        if ($ord0 >= 192 && $ord0 <= 223) {
            return ($ord0 - 192) * 64 + ($ord1 - 128);
        }
        $ord2 = ord($utf8char{2});
        if ($ord0 >= 224 && $ord0 <= 239) {
            return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128);
        }
        $ord3 = ord($utf8char{3});
        if ($ord0 >= 240 && $ord0 <= 247) {
            return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128);
        }
        return false;
    }
813372
function utf16to8(e) {
    var t, n, r, i;

    t = '';
    r = e.length;

    for (n = 0; n < r; n++) {
        i = e.charCodeAt(n);

        if (i >= 1 && i <= 127) {
            t += e.charAt(n);
        } else if (i > 2047) {
            t += String.fromCharCode(224 | i >> 12 & 15);
            t += String.fromCharCode(128 | i >> 6 & 63);
            t += String.fromCharCode(128 | i >> 0 & 63);
        } else {
            t += String.fromCharCode(192 | i >> 6 & 31);
            t += String.fromCharCode(128 | i >> 0 & 63);
        }
    }

    return t;
}
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;
	}
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;
		}
	}
1063659
public static String encode(String str)
	{
		try
		{
			return java.net.URLEncoder.encode(str, "UTF-8");
		}
		catch(java.io.UnsupportedEncodingException ue)
		{
			return str;
		}
	}
1344191
private static function utf8chr($c)
    {
        if (0x80 > $c %= 0x200000) {
            return chr($c);
        }
        if (0x800 > $c) {
            return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
        }
        if (0x10000 > $c) {
            return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
        }

        return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
    }
444103
public static function iconv_fallback_utf8_iso88591($string) {
		if (function_exists('utf8_decode')) {
			return utf8_decode($string);
		}
		// utf8_decode() unavailable, use getID3()'s iconv_fallback() conversions (possibly PHP is compiled without XML support)
		$newcharstring = '';
		$offset = 0;
		$stringlength = strlen($string);
		while ($offset < $stringlength) {
			if ((ord($string{$offset}) | 0x07) == 0xF7) {
				// 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
				$charval = ((ord($string{($offset + 0)}) & 0x07) << 18) &
						   ((ord($string{($offset + 1)}) & 0x3F) << 12) &
						   ((ord($string{($offset + 2)}) & 0x3F) <<  6) &
							(ord($string{($offset + 3)}) & 0x3F);
				$offset += 4;
			} elseif ((ord($string{$offset}) | 0x0F) == 0xEF) {
				// 1110bbbb 10bbbbbb 10bbbbbb
				$charval = ((ord($string{($offset + 0)}) & 0x0F) << 12) &
						   ((ord($string{($offset + 1)}) & 0x3F) <<  6) &
							(ord($string{($offset + 2)}) & 0x3F);
				$offset += 3;
			} elseif ((ord($string{$offset}) | 0x1F) == 0xDF) {
				// 110bbbbb 10bbbbbb
				$charval = ((ord($string{($offset + 0)}) & 0x1F) <<  6) &
							(ord($string{($offset + 1)}) & 0x3F);
				$offset += 2;
			} elseif ((ord($string{$offset}) | 0x7F) == 0x7F) {
				// 0bbbbbbb
				$charval = ord($string{$offset});
				$offset += 1;
			} else {
				// error? throw some kind of warning here?
				$charval = false;
				$offset += 1;
			}
			if ($charval !== false) {
				$newcharstring .= (($charval < 256) ? chr($charval) : '?');
			}
		}
		return $newcharstring;
	}
410516
public function filter($string)
    {
        // Only operate on valid UTF-8 strings. This is necessary to prevent cross
        // site scripting issues on Internet Explorer 6.
        if (!$this->isUtf8($string)) {
            return '';
        }

        // Remove NULL characters (ignored by some browsers).
        $string = str_replace(chr(0), '', $string);

        // Remove Netscape 4 JS entities.
        $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);

        // Defuse all HTML entities.
        $string = str_replace('&', '&amp;', $string);

        // Change back only well-formed entities in our whitelist:
        // Decimal numeric entities.
        $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);

        // Hexadecimal numeric entities.
        $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);

        // Named entities.
        $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);

        return (string) preg_replace_callback('%
            (
            <(?=[^a-zA-Z!/])  # a lone <
            |                 # or
            <!--.*?-->        # a comment
            |                 # or
            <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
            |                 # or
            >                 # just a >
            )%x', array($this, 'build'), $string);
    }