Reputation:
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.
Upvotes: 0
Views: 849
Reputation: 423
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.
Upvotes: 2
Reputation: 79069
You can use HTML Tidy to solve this problem. To finds and closes the unclosed tags, automatically.
Upvotes: 0