安全的擷取指定長度的html或者ubb字串

2021-09-05 22:23:14 字數 930 閱讀 7428

在將html**輸出到頁面時,有時候會需要截斷字串保留指定長度的字串,由於html中有些標籤必須成對出現,所以在擷取html時需要特別注意,不能因為截斷問題把頁面搞亂掉。

在擷取字串時需要記錄每乙個標籤是否關閉,如果擷取到指定長度還有沒有關閉的標籤,那麼我們需要將標籤關閉,或者刪除掉未關閉的標籤。不考慮某些不需要關閉標籤的情況,html開始和結束標籤總是成對出現的,我們可以遍歷輸入的字串,並在標籤開始時放入堆疊中,遇到結束標籤時從堆疊中彈出乙個元素,這樣遍歷到指定長度,堆疊中留下的標籤就是需要補全或者刪除掉的標籤。

static char end_slash = '/';

/// /// 安全的截斷字串

///

/// 輸入串

/// 截斷長度

/// true:截斷半截標籤;false:補全半截標籤

/// 標籤開始字元

/// 標籤結束字元

/// 需要關閉的標籤陣列

/// length長度的字串

public static string safetrim(string input, int length, bool trimhalftag, char tagstartchar, char tagendchar, string mustclosetags)

if (!istagnameend)

else

}if (!string.isnullorempty(tag))

else

hasmarktaginstack = true;}}

if (istagnameend)}}

}else

}while (tags.count > 0)

}if (ismustclosetag)

else}}

return result;

}

擷取指定長度html內容,並保留html格式標記

按位元組長度擷取字串 支援擷取帶html 樣式的字串 將要擷取的字串引數 擷取的位元組長度 字串末尾補上的字串 返回擷取後的字串 public string substringtohtml string param,int length,string end else if temp else if...

擷取指定長度的字串

函式說明 擷取指定長度的字串 utf 8專用 漢字和大寫字母長度算1,其它字元長度算0.5 param string str 原字串 param int len 擷取長度 param string etc 省略字元.return string 擷取後的字串 if function exists re...

新聞標題擷取指定長度加

首先的頁面的cs檔案中宣告這樣的乙個方法 public static string getsubstring string str if str.length 10 string str1 str.substring 0,10 return str1 else return str1 就是說如果長度...