将Unicode字符'POPCORN'转义为HTML实体

时间:2019-08-17 01:36:48

标签: java apache-commons html-escape-characters unicode-escapes

我有一个带有表情符号的字符串

I love ?

我需要用它的html实体来逃避爆米花表情符号,所以我得到了

I love 🍿

我正在用Java编写代码,并且一直在尝试使用不同的StringEscapeUtils库,但尚未使其工作。请帮我弄清楚我可以用来转义爆米花等特殊字符的方法。

供参考:

Unicode Character Information

Unicode 8.0 (June 2015)

4 个答案:

答案 0 :(得分:2)

这有点hacky,因为我不相信有现成的库可以做到这一点;假设您不能在HTML页面上简单地使用UTF-8(或UTF-16)(应该可以按原样呈现?),则可以使用Character.codePointAt(CharSequence, int)Character.offsetByCodePoints(CharSequence, int, int) 1 在给定字符超出正常ASCII范围的情况下执行转换。像

String str = "I love ?";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch > 127) {
        sb.append(String.format("&#x%x;", Character.codePointAt(str, i)));
        i += Character.offsetByCodePoints(str, i, 1) - 1;
    } else {
        sb.append(ch);
    }
}
System.out.println(sb);

输出(根据要求)

I love &#x1f37f;

1 根据Andreas的helpful comments编辑。

答案 1 :(得分:1)

通常emoji4j library有效。它具有用于HTML编码的简单htmlify方法。

例如:

String text = "I love ?";

EmojiUtils.htmlify(text); //returns "I love &#127871"

EmojiUtils.hexHtmlify(text); //returns "I love &#x1f37f"

答案 2 :(得分:1)

您可以使用unbescape库:unbescape: powerful, fast and easy escape/unescape operations for Java

示例

将依赖项添加到pom.xml文件中:

<dependency>
    <groupId>org.unbescape</groupId>
    <artifactId>unbescape</artifactId>
    <version>1.1.6.RELEASE</version>
</dependency>

用法:

import org.unbescape.html.HtmlEscape;
import org.unbescape.html.HtmlEscapeLevel;
import org.unbescape.html.HtmlEscapeType;

<…>

final String inputString = "\uD83C\uDF7F";
final String escapedString = HtmlEscape.escapeHtml(
    inputString,
    HtmlEscapeType.HEXADECIMAL_REFERENCES,
    HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT
);

// Here `escapedString` has the value: `&#x1f37f;`.

对于您的用例,可能应该使用HtmlEscapeType.HTML4_NAMED_REFERENCES_DEFAULT_TO_HEXAHtmlEscapeType.HTML5_NAMED_REFERENCES_DEFAULT_TO_HEXA而不是HtmlEscapeType.HEXADECIMAL_REFERENCES

答案 3 :(得分:1)

我将使用CharSequence::codePoints来获取IntStream的代码点,并将它们映射到字符串,然后收集它们,并连接为单个字符串:

public String escape(final String s) {
    return s.codePoints()
        .mapToObj(codePoint -> codePoint > 127 ?
            "&#x" + Integer.toHexString(codePoint) + ";" :
             new String(Character.toChars(codePoint)))
    .collect(Collectors.joining());
}

对于指定的输入,将产生:

I love &#x1f37f;