asp.net 安全的截取指定长度的html或者ubb字符串_实用技巧

分享到:
在截取字符串时需要记录每一个标签是否关闭,如果截取到指定长度还有没有关闭的标签,那么我们需要将标签关闭,或者删除掉未关闭的标签。不考虑某些不需要关闭标签的情况,html开始和结束标签总是成对出现的,我们可以遍历输入的字符串,并在标签开始时放入堆栈中,遇到结束标签时从堆栈中弹出一个元素,这样遍历到指定长度,堆栈中留下的标签就是需要补全或者删除掉的标签。

下面是代码实现,如果大家有更好的方法请给出来:

static char END_SLASH = '/';

/// <summary>
/// 安全的截断字符串
/// </summary>
/// <param name="input">输入串</param>
/// <param name="length">截断长度</param>
/// <param name="trimHalfTag">true:截断半截标签;false:补全半截标签</param>
/// <param name="tagStartChar">标签开始字符</param>
/// <param name="tagEndChar">标签结束字符</param>
/// <param name="mustCloseTags">需要关闭的标签数组</param>
/// <returns>length长度的字符串</returns>
public static string SafeTrim(string input, int length, bool trimHalfTag, char tagStartChar, char tagEndChar, string[] mustCloseTags)
{
if (length <= 0) throw new ArgumentException("length 必须是正数");
if (mustCloseTags == null) throw new ArgumentNullException("mustCloseTags");

int inputLen = input.Length;
if (string.IsNullOrEmpty(input) || inputLen <= length) return input;

string result = string.Empty;

//声明堆栈用来放标签
Stack<string> tags = new Stack<string>();

for (int i = 0; i < length; i++)
{
char c = input[i];

if (c == tagStartChar)
{
string tag = string.Empty;
int tagIndex = i + 1;
bool isTagEnd = false;
bool isTagNameEnd = false;
result += c;
bool hasMarkTagInStack = false;
while (tagIndex < inputLen)
{
char tagC = input[tagIndex];
result += tagC;
tagIndex++;
if (tag == string.Empty && tagC == END_SLASH)
{
isTagEnd = true;
continue;
}
if (!isTagNameEnd)
{
if (char.IsLetter(tagC) || char.IsNumber(tagC))
{
tag += tagC;
}
else
{
isTagNameEnd = true;
}
}

if (!string.IsNullOrEmpty(tag))
{
if (isTagNameEnd && !hasMarkTagInStack)
{
if (isTagEnd)
{
tags.Pop();
}
else
{
tags.Push(tag);
}
hasMarkTagInStack = true;
}
}

if (isTagNameEnd)
{
if (tagC == tagEndChar)
{
i = tagIndex - 1;
break;
}
}

}
}
else
{
result += c;
}
}

while (tags.Count > 0)
{
string tag = tags.Pop();

bool isMustCloseTag = false;
foreach (string mustCloseTag in mustCloseTags)
{
if (string.Compare(mustCloseTag, tag, true) == 0)
{
isMustCloseTag = true;
break;
}
}
if (isMustCloseTag)
{
if (trimHalfTag)
{
int lastTagIndex = result.LastIndexOf(tagStartChar.ToString() + tag, StringComparison.CurrentCultureIgnoreCase);

result = result.Substring(0, lastTagIndex);
}
else
{
result += (tagStartChar.ToString() + END_SLASH + tag + tagEndChar);
}
}
}

return result;
}

转载请保留链接 玉开的技术博客
昵    称:
验证码: