0

我允许用户使用<pre></pre>标签在评论和文章中显示代码,但我遇到了一个我正在努力解决的问题。当用户未能关闭 HTML 标记时,例如:

    <pre>
        <html>
            <head>

            </head>
    </pre>

评论似乎是空白的。我正在寻找的是某种功能,它会自动关闭用户错过的任何 HTML 标记。

提前致谢。

4

2 回答 2

2

好吧,如果您不使用框架,那将变得令人讨厌,但是您的勇气令人钦佩。希望这将推动正确的方向。

我能想到的最简单的非框架解决方案是在解析来自用户的字符串时使用堆栈来推送和弹出标签。

伪代码

userData = getUserData();
stack = array();
loop (line in userData) {
   matches = search for "<*>"; // may have multiple on one line
   loop (match in matches) {
      tagName = getTagNameFrom(match);
      if ("/" is not found) {
         push tagName on stack;
      } else if ("/" is found) {
         pop tagName off stack; 
         // There was an error if the stack is
         // empty or the tagName that was popped was not
         // the same.
      }
   }
}

This is by no means comprehensive and a framework is really recommended here, but hopefully it can help out a bit.

于 2012-04-04T00:08:02.397 回答
0

您可以使用 HTML Tidy 来解决这个问题。自动查找并关闭未关闭的标签。

项目页面

于 2012-04-03T23:48:06.693 回答