Convert all applicable characters to HTML entities..
does not double encode

@param string  $str        string
@param boolean $encodeTags [true]
@param boolean $isXml      [false]
@param string  $charset    [null]

@return string
503266
public static function htmlentities($str = '', $encodeTags = true, $isXml = false, $charset = null)
    {
        $debug = \bdk\Debug::getInstance();
        $dbWas = $debug->setCfg('collect', false);
        $debug->groupCollapsed(__FUNCTION__);
        $return = '';
        $charsetsTry = array('UTF-8','ISO-8859-1');
        $debug->log('charset', $charset);
        if (is_null($charset) && extension_loaded('mbstring')) {
            $charset = mb_detect_encoding($str, mb_detect_order(), true);
            $debug->log('charset detected', $charset);
        }
        if ($charset) {
            $charset = self::getCharset($charset);
            if ($charset == 'UTF-8' && !Str::isUtf8($str)) {
                $charset = null;
            }
        }
        if ($charset) {
            #$debug->log('will try charset '.$charset.' first');
            array_unshift($charsetsTry, $charset);
            $charsetsTry = array_unique($charsetsTry);
        }
        $debug->log('charsetsTry', implode(', ', $charsetsTry));
        $return = self::htmlentitiesApply($str, $encodeTags, $isXml, $charsetsTry);
        #$debug->log('return', $return);
        $debug->groupEnd();
        $debug->setCfg('collect', $dbWas);
        return $return;
    }
1167635
function encodeMimeHeader( $str )
    {
        if ( !$this->TextCodec )
        {
             $this->TextCodec = eZTextCodec::instance( $this->contentCharset(), $this->outputCharset() );
        }

        if ( function_exists( "mb_encode_mimeheader" ) )
        {
            $encoded = mb_encode_mimeheader( $str, $this->TextCodec->InputCharsetCode, "B", eZMail::lineSeparator() );
        }
        else
        {
            if (  0 == preg_match_all( '/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches ) )
                return $str;

            $maxlen = 75 - 7 - strlen( $this->TextCodec->InputCharsetCode );

            $encoding = 'B';
            $encoded = base64_encode( $str );
            $maxlen -= $maxlen % 4;
            $encoded = trim( chunk_split( $encoded, $maxlen, "\n" ) );

            $encoded = preg_replace( '/^(.*)$/m', " =?".$this->TextCodec->InputCharsetCode."?$encoding?\\1?=", $encoded );

            $encoded = trim( str_replace( "\n", eZMail::lineSeparator(), $encoded ) );
        }

        return $encoded;
    }
333288
public static function xmlDecode(string $str): array {
		$data       = null;
		$xml_parser = xml_parser_create();
		if (xml_parse($xml_parser, $str, true))
			$data = (json_decode(json_encode(simplexml_load_string($str)), true));
		xml_parser_free($xml_parser);
		if (is_null($data))
			throw new DecodeXMLException;
		return $data;
	}
932150
public function escapeHTML(?string $string, string $charset, bool $doubleEncode = true): string
	{
		return htmlspecialchars($string, ENT_QUOTES, $charset, $doubleEncode);
	}
773332
public static function decode(String $str) : String
    {
        return str_replace(array_values(self::$phpTagChars), array_keys(self::$phpTagChars), $str);
    }
870804
def xml_encode string
      puts string.each_char.size
      string.each_char.map do |p|
        case 
        when CONVERTIBLES[p]
          CONVERTIBLES[p]
        when XML_ENTITIES[p]
          "&##{XML_ENTITIES[p]};"
        else
          p
        end
      end.reduce(:+)
    end
16520
protected function strtoupper($str)
    {
        $str = html_entity_decode($str, $this->htmlFuncFlags, self::ENCODING);
        $str = mb_strtoupper($str);
        $str = htmlspecialchars($str, $this->htmlFuncFlags, self::ENCODING);

        return $str;
    }
66705
function(str) {
		var xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'}, xmlEncodeRegExp = /[<>&\"\']/g;

		return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) {
			return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr;
		}) : str;
	}
171386
public static function html_identifier($str, $encode=false)
    {
        if ($encode) {
            return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
        }
        else {
            return asciiwords($str, true, '_');
        }
    }
169611
public function toString($isXML = true)
    {
        // Keep the formatting value.
        $formatOutput = $this->domDocument->formatOutput;
        // Format if the output will be XML.
        $this->domDocument->formatOutput = $isXML;
        // Get the XML in a string.
        $xmlString = $isXML
            ? $this->domDocument->saveXML()
            : $this->domDocument->saveHTML();
        // Restore the output formatting value.
        $this->domDocument->formatOutput = $formatOutput;

        // If the document has been saved as HTML, tags that do not need closing
        // in HTML will be duplicated, as a result of the closing tag being
        // correctly interpreted by HTML browsers as another tag. For instance,
        // <br /> will be converted to <br></br>, which the browser will
        // interpret as two <br> tags.
        if (!$isXML) {
            $xmlString = preg_replace('#></(?:br)>#', ' />', $xmlString);
        }

        return $xmlString;
    }
1294666
static function realstring($str,$encode='utf8')
    {
        if($encode=='utf8') $n = preg_match('/^[\x{4e00}-\x{9fa5}|a-z|0-9|A-Z]+$/u',$str,$match);
        else $n = preg_match("/^[".chr(0xa1)."-".chr(0xff)."|a-z|0-9|A-Z]+$/",$str,$match);
        if($n===0) return false;
        else return $match[0];
    }
944551
public function encodeHeader($str, $position = 'text')
    {
        $matchcount = 0;
        switch (strtolower($position)) {
            case 'phrase':
                if (!preg_match('/[\200-\377]/', $str)) {
                    // Can't use addslashes as we don't know the value of magic_quotes_sybase
                    $encoded = addcslashes($str, "\0..\37\177\\\"");
                    if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
                        return ($encoded);
                    } else {
                        return ("\"$encoded\"");
                    }
                }
                $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'comment':
                $matchcount = preg_match_all('/[()"]/', $str, $matches);
            // Intentional fall-through
            case 'text':
            default:
                $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
                break;
        }

        if ($matchcount == 0) { // There are no chars that need encoding
            return ($str);
        }

        $maxlen = 75 - 7 - strlen($this->CharSet);
        // Try to select the encoding which should produce the shortest output
        if ($matchcount > strlen($str) / 3) {
            // More than a third of the content will need encoding, so B encoding will be most efficient
            $encoding = 'B';
            if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
                // Use a custom function which correctly encodes and wraps long
                // multibyte strings without breaking lines within a character
                $encoded = $this->base64EncodeWrapMB($str, "\n");
            } else {
                $encoded = base64_encode($str);
                $maxlen -= $maxlen % 4;
                $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
            }
        } else {
            $encoding = 'Q';
            $encoded = $this->encodeQ($str, $position);
            $encoded = $this->wrapText($encoded, $maxlen, true);
            $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
        }

        $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
        $encoded = trim(str_replace("\n", $this->LE, $encoded));

        return $encoded;
    }
1270569
static function DecodeFromHTML($string, $charset = null)
	{
		// this only gets named characters
		// return html_entity_decode($string);

		// this is a complex method that appears to be the reverse of UTF8ToHTML
		// taken from http://www.php.net/manual/en/function.html-entity-decode.php#68491
//		$string = self::ReplaceNonNumericEntities($string);
//		$string = preg_replace_callback('~&(#(x?))?([^;]+);~', 'self::html_entity_replace', $string);
//        return $string;

		// this way at least somebody could specify a character set.  UTF-8 will work most of the time
		if ($charset == null) $charset = VerySimpleStringUtil::$DEFAULT_CHARACTER_SET;
		return mb_convert_encoding($string, $charset, 'HTML-ENTITIES');
	}
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;
    }
82265
private function _strtoupper($str)
    {
        $str = html_entity_decode($str, ENT_COMPAT);

        if (function_exists('mb_strtoupper')) {
            $str = mb_strtoupper($str, 'UTF-8');
        } else {
            $str = strtoupper($str);
        }

        $str = htmlspecialchars($str, ENT_COMPAT);

        return $str;
    }
683181
public function encodeHtmlChars($s, $flags = null, $encode = null, $double_encode = false)
    {
        if ($flags === null) {
            $flags = ENT_COMPAT;
        }
        if ($encode === null) {
            $encode = ini_get('default_charset') ?: 'UTF-8';
        }

        return htmlspecialchars($s, $flags, $encode, $double_encode);
    }
795934
public function htmlEncode($string, $quoteStyle = ENT_QUOTES, $charset = 'UTF-8', $doubleEncode = false)
    {
        return htmlspecialchars((string) $string, $quoteStyle, $charset, $doubleEncode);
    }