自动关闭HTML标签 [英] Closing HTML Tags Automatically
问题描述
我允许用户使用< pre>< / pre>
标签在评论和文章中显示代码,但我遇到了一个问题我正在努力解决。例如:当用户未能关闭HTML标签时,例如:
< pre>
< html>
< head>
< / head>
< / pre>
注释显示为空白。我正在寻找的是某种功能,它会自动关闭用户错过的任何HTML标记。
预先感谢。
好吧,如果你不使用框架,但是你的勇气会被钦佩,那么它会变得令人讨厌。希望这将是一个正确的方向。
我能想到的最简单的非框架解决方案是在解析字符串时使用堆栈来推送和弹出标签
$ b 伪代码
userData = getUserData();
stack = array();
循环(userData中的行){
matches =搜索<>; //可能在一行上有多个
循环(在匹配中匹配){
tagName = getTagNameFrom(match);
if(/未找到){
在堆栈上push tagName;
} else if(/is found){
pop tagName off stack;
//如果堆栈是
//空,或者弹出的tagName不是
//相同,则出现错误。
}
}
}
这绝不是全面的并且在这里真的推荐一个框架,但希望它可以帮助一下。
I've allowed users to use <pre></pre>
tags to display code in comments and articles, but I've come across a problem that I'm struggling to solve. When a user fails to close an HTML tag, for example:
<pre>
<html>
<head>
</head>
</pre>
the comment appears to be blank. What I'm looking for is some sort of function that will automatically close any HTML tags that the user missed.
Thanks in advance.
Well it's going to get nasty if you dont use a framework but your courage is admired. Hopefully this will be a nudge in the right direction.
The simplest, non-framework solution I can think of is using a stack to push and pop tags while parsing the string from the user.
pseudo code
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.
这篇关于自动关闭HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!