How to replace accented characters by their HTML representation

我的未来我决定 提交于 2019-12-08 06:38:28

问题


I would like to transform strings like "rég" to "grégou".

I temporarily wrote some code that manually changes the most common accents, but I would like to get one that transforms each accent to its html equivalent.

Someone has an idea? :)

ps: I tried something but it does not work ...

C # code:

public static MvcHtmlString MyEncode(this HtmlHelper htmlHelper, string text)
{
    StringBuilder builder = new StringBuilder();
    Byte[] bArray;


    HttpUtility.HtmlEncode(text);

    bArray = System.Text.Encoding.GetEncoding(850).GetBytes(text); 

    String chaine = "";


    for(int i=0; i<bArray.Length; i++)
    {
        chaine = chaine + (char)bArray[i];
    }

    HttpUtility.HtmlEncode(chaine);
    builder.Append(chaine);
    return MvcHtmlString.Create(builder.ToString());
}

--OLD


回答1:


The HttpUtility.HtmlEncode Method does not modify the argument (strings in C# are immutable!); it returns the encoded version as a new string:

string encoded = HttpUtility.HtmlEncode("rég");

The preferred way to encode text in the context of MVC seems to be the Html.Encode Helper Method:

<%= Html.Encode("rég") %>



回答2:


The library HelperSharp has a method for this purpose: EscapeAccentsToHtmlEntities

// The result will be: gr&eacute;gou
var escaped = "grégou".EscapeAccentsToHtmlEntities(); 



回答3:


A quick google search for "HTML entity encode C#" brings up lots of hits ... like the following:

http://www.codeproject.com/KB/recipes/htmlencodingcsharp.aspx

There are also framework classes that perform this function:

http://msdn.microsoft.com/en-us/library/73z22y6h.aspx



来源:https://stackoverflow.com/questions/6291316/how-to-replace-accented-characters-by-their-html-representation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!