简体   繁体   English

如何仅将特殊字符转换为 html 实体而不转义 <、>、" 和 '?

[英]How to convert only special characters to html entities without escaping <, >, " and '?

I need to escape special characters in mail to html5 entities, because, even if the mail is sent as utf8, some client mails does not display them correctly.我需要将邮件中的特殊字符转义为 html5 实体,因为即使邮件以 utf8 格式发送,某些客户端邮件也无法正确显示它们。 I don't want to use entities directly in the mail, since the mail are made by testers and we don't want to enforce testers to learn all html5 entities.我不想直接在邮件中使用实体,因为邮件是由测试人员制作的,我们不想强制测试人员学习所有 html5 实体。

I tried to use我试着用

org.unbescape.html.HtmlEscape.escapeHtml​(
    string, 
    HtmlEscapeType.HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL,
    HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT
)

link 关联

but they both escape also < , > , " and ' characters.但它们都可以转义<>"'字符。

Now I'm using this self-made method:现在我正在使用这种自制的方法:

public static final String encodeHTML(final String s) {
    String res = HtmlEscape.escapeHtml(
        s, 
        HtmlEscapeType.HTML5_NAMED_REFERENCES_DEFAULT_TO_DECIMAL,
        HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT
    );

    res = res.replaceAll("&lt;", "<");
    res = res.replaceAll("&gt;", ">");
    res = res.replaceAll("&quot;", "\"");
    res = res.replaceAll("&apos;", "'");
    res = res.replaceAll("&amp;", "&");

    return res;
}

Example:例子:

encodeHTML("<div id='a' class\"ciao\">&amp; ®</div>")

outputs:输出:

<div id='a' class"ciao">&amp; &reg;</div>

That's what I want, but there's not something more standard?这就是我想要的,但没有更标准的东西吗?

Following code help you to convert only special characters.以下代码可帮助您仅转换特殊字符。

import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.text.translate.AggregateTranslator;
import org.apache.commons.text.translate.EntityArrays;
import org.apache.commons.text.translate.LookupTranslator;

public String encodeHTML(String s) {

    StringEscapeUtils.Builder buider =StringEscapeUtils
        .builder(new AggregateTranslator(new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE),
            new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE)));

    return buider.escape(s).toString();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM