Here is a great answer to a similar question. You'll have to count tags and add whichever ones are truncated.
pseudo code
userData = getUserInput();
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.
}
}
}
foreach tagName in stack {
userdata += "</" + tagName + ">";
}
By the way, your webpage sounds really vulnerable to XSS.