3

我有以下输入:

Hi! How are you? <script>//NOT EVIL!</script>

Wassup? :P

LOOOL!!! :D :D :D

然后通过表情库运行,它变成了这样:

Hi! How are you? <script>//NOT EVIL!</script>

Wassup? <img class="smiley" alt="" title="tongue, :P" src="ui/emoticons/15.gif">

LOOOL!!! <img class="smiley" alt="" title="big grin, :D" src="ui/emoticons/5.gif"> <img class="smiley" alt="" title="big grin, :P" src="ui/emoticons/5.gif"> <img class="smiley" alt="" title="big grin, :P" src="ui/emoticons/5.gif">

我有一个转义 HTML 实体以防止 XSS 的功能。因此,在第一行的原始输入上运行它会产生:

Hi! How are you? &lt;script&gt;//NOT EVIL!&lt;/script&gt;

现在我需要转义所有输入,但同时我需要将表情符号保留在初始状态。因此,当有<:-P表情符号时,它会保持不变,不会变成&lt;:-P

我正在考虑对表情符号进行正则表达式拆分。然后单独处理每个部分,然后将字符串连接在一起,但我不确定 Regex 是否容易被绕过?我知道格式永远是这样的:

[<img class="smiley" alt="]
[empty string]
[" title="]
[one of the values from a big list]
[, ]
[another value from the list (may be matching original emoticon)]
[" src="ui/emoticons/]
[integer from Y to X]
[.gif">]

使用列表可能会很慢,因为我需要在可能有 20-30-40 个表情符号的文本上运行该正则表达式。另外,可能需要处理 5-10-15 条短信。什么可能是一个优雅的解决方案?我准备为此使用第三方库或 jQuery。PHP 预处理也是可能的。

4

1 回答 1

2

也许这会帮助你:

//TODO:Add the rest of emoticons here
var regExpEmoticons = /(\:P|\:\-P|\:D|\:\-D)/img;

function emoticonTag(title, filename) {
    return "<img class=\"smiley\" alt=\"\" title=\"" + title + "\" src=\"ui/emoticons/" + filename + "\">";
}

function replaceEmoticon(emoticon) {
    switch (emoticon.toUpperCase()) {
    case ':P':
    case ':-P':
        return emoticonTag("tongue, :P", "15.gif");
    case ':D':
    case ':-D':
        return emoticonTag("big grin, :D", "5.gif");
    //TODO: Add more emoticons
    }
}

function escapeHtml(string) {
    //TODO: Insert your HTML escaping code here
    return string;
}

function escapeString(string) {
    if (string == "") {
        return string;
    }
    var splittedString = string.split(regExpEmoticons);

    var result = "";
    for (var i = 0; i < splittedString.length; i++) {
        if (splittedString[i].match(regExpEmoticons)) {
            result += replaceEmoticon(splittedString[i]);
        } else {
            result += escapeHtml(splittedString[i]);
        }
    }
    return result;
}

有3个地方你必须改变:

  1. 将所有表情符号添加到regExpEmoticons变量中。
  2. 将所有表情符号添加到函数switch语句中replaceEmoticon,或将整个函数更改为仅将表情符号字符串替换为包含标记的 HTML 字符串的函数。
  3. 将您的 HTML 转义代码添加到escapeHtml函数中,或将对该函数的调用更改为您正在使用的函数。

之后,如果你escapeString用你的字符串调用方法,我认为它会起作用。

于 2013-10-24T22:30:30.327 回答