【发布时间】:2015-09-02 19:27:22
【问题描述】:
我有以下方法使用C#替换字符串中的表情符号
public static string Emotify(string inputText)
{
var emoticonFolder = EmoticonFolder;
var emoticons = new Hashtable(100)
{
{":)", "facebook-smiley-face-for-comments.png"},
{":D", "big-smile-emoticon-for-facebook.png"},
{":(", "facebook-frown-emoticon.png"},
{":'(", "facebook-cry-emoticon-crying-symbol.png"},
{":P", "facebook-tongue-out-emoticon.png"},
{"O:)", "angel-emoticon.png"},
{"3:)", "devil-emoticon.png"},
{":/", "unsure-emoticon.png"},
{">:O", "angry-emoticon.png"},
{":O", "surprised-emoticon.png"},
{"-_-", "squinting-emoticon.png"},
{":*", "kiss-emoticon.png"},
{"^_^", "kiki-emoticon.png"},
{">:(", "grumpy-emoticon.png"},
{":v", "pacman-emoticon.png"},
{":3", "curly-lips-emoticon.png"},
{"o.O", "confused-emoticon-wtf-symbol-for-facebook.png"},
{";)", "wink-emoticon.png"},
{"8-)", "glasses-emoticon.png"},
{"8| B|", "sunglasses-emoticon.png"}
};
var sb = new StringBuilder(inputText.Length);
for (var i = 0; i < inputText.Length; i++)
{
var strEmote = string.Empty;
foreach (string emote in emoticons.Keys)
{
if (inputText.Length - i >= emote.Length && emote.Equals(inputText.Substring(i, emote.Length), StringComparison.InvariantCultureIgnoreCase))
{
strEmote = emote;
break;
}
}
if (strEmote.Length != 0)
{
sb.AppendFormat("<img src=\"{0}{1}\" alt=\"\" class=\"emoticon\" />", emoticonFolder, emoticons[strEmote]);
i += strEmote.Length - 1;
}
else
{
sb.Append(inputText[i]);
}
}
return sb.ToString();
}
它工作得很好并且“看起来”相当快,但是我意识到 Html 有一个小问题。
此方法会破坏带有链接的页面,因为...
:/
表情符号。它打破了
http://
通过在中间粘贴图像。我正在尝试找出一种方法来调整此方法以考虑链接并忽略它们 - 但不会牺牲性能。
非常感谢任何帮助或指点。
【问题讨论】:
-
您是否考虑过使用正则表达式匹配以便只查看字符串或忽略带有 http(s):/ 的字符串?
-
在谈论 HTML 时要考虑的另一件事:是 ">:(" 脾气暴躁,还是说是紧跟着皱眉头?只是问,让你考虑一下。
-
使用通用版本
Dictionary<string, string>,而不是HashTable。 -
stackoverflow.com/questions/15944495/…(PHP,但无论如何都将建议用于 C# 的相同方法,因此请抢占先机)。当您想要检测表情符号时,还可以考虑为自己澄清 - 可能是周围的空白?通常 HTMLAgilityPack 将是有用的开始,但它不会有太大帮助,因为文本可以包含 HTML 和各种编码的
&gt;)文本。 -
您可以创建一个
List<string>或keywords,它会在转换为表情之前对其进行检查。它将获取找到的表情符号,并检查周围的字符以查看它是否与关键字匹配。如果是这样,请忽略它并继续。
标签: c# replace indexof emoticons