asp.net 安全的截取指定長度的html或者ubb字串

來源:互聯網
上載者:User

在截取字串時需要記錄每一個標籤是否關閉,如果截取到指定長度還有沒有關閉的標籤,那麼我們需要將標籤關閉,或者刪除掉未關閉的標籤。不考慮某些不需要關閉標籤的情況,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;
}

轉載請保留連結 玉開的技術部落格

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.