2013年3月20日 星期三

節略HTML文字(文字內容包含連結等Tag)

有幾種可能的處理方式,分述如下:

  1. 前端<Div>的方式
<div style="width:450px; height: 18px;
         overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
         <asp:Label ID="Notice" runat="server" class="txt" />
</div>

    2.  Div配合綁定


<div title='<%# Eval("Notice") %>' style="cursor: hand; width: 153px; height: 20px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
<asp:LinkButton ID="ClassTitle" runat="server" Text='<%# Eval("Notice") %>' />

    3.  Div配合綁定與程式


<div id="GroupNameDiv" runat="server" style="cursor: hand; width: 153px; height: 20px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
<asp:Label ID="GroupName" runat="server" Text='' CssClass="txt"></asp:Label>&nbsp;
</div>                            
HtmlGenericControl GroupNameDiv = e.Item.FindControl("GroupNameDiv") as HtmlGenericControl;
GroupNameDiv.Attributes["title"] = GroupName.Text;

    4.  程式方式


int length = Regex.Replace(eItem.Content, "(?is)<.+?>", "").Length;
if (length < 40)
{
    Notice.Text = HtmlSubstring(eItem.Content, length);
}
else
{
    Notice.Text = HtmlSubstring(eItem.Content, 40) + "...";
}
public static string HtmlSubstring(string html, int maxlength)
{
    //initialize regular expressions
    string htmltag = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>";
    string emptytags = "<(\\w+)((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?></\\1>";
    //match all html start and end tags, otherwise get each character one by one..
    var expression = new Regex(string.Format("({0})|(.?)", htmltag));
    MatchCollection matches = expression.Matches(html);
    int i = 0;
    StringBuilder content = new StringBuilder();
    foreach (Match match in matches)
    {
        if (match.Value.Length == 1
            && i < maxlength)
        {
            content.Append(match.Value);
            i++;
        }
        //the match contains a tag
        else if (match.Value.Length > 1)
            content.Append(match.Value);
    }
    return Regex.Replace(content.ToString(), emptytags, string.Empty);
}

沒有留言:

張貼留言