繁体   English   中英

替换字符串中的HTML实体避免 <img> 标签

[英]Replace HTML entities in a string avoiding <img> tags

我有以下输入:

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 entites的功能来阻止XSS。 因此,在第一行的原始输入上运行它将产生:

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

现在我需要逃避所有输入,但同时我需要保持表情符号处于初始状态。 所以当有<:-P emoticon时,它就会保持这种状态,并且不会变成&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预处理也是可能的。

也许这会对你有所帮助:

//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. 将所有表情符号添加到replaceEmoticon函数的switch语句中,或者将您的表情符号的整个函数更改为仅将表情符号字符串替换为包含该标记的HTML字符串。
  3. 将HTML转义代码添加到escapeHtml函数中,或将对此函数的调用更改为您正在使用的函数。

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

暂无
暂无

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

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