データベースにいくつかの記事が保存されています。特定のページでは、いくつかの設定に基づいて記事の特定の割合を表示したいと考えていました。例: 記事の 80%
問題は、文字列の長さの特定の割合を使用するとhtmlがプレーンテキストではないため、フォーマットが乱れることです。私が試した書式設定を乱すことなく、切り捨てられた html を返します
Private Function HtmlSubstring(html As String, maxlength As Integer) As String
'initialize regular expressions
Dim htmltag As String = "</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>"
Dim emptytags As String = "<(\w+)((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?></\1>"
'match all html start and end tags, otherwise get each character one by one..
Dim expression As Regex = New Regex(String.Format("({0})|(.?)", htmltag))
Dim matches As MatchCollection = expression.Matches(html)
Dim i As Integer = 0
Dim content As New StringBuilder()
For Each match As Match In matches
If match.Value.Length = 1 AndAlso i < maxlength Then
content.Append(match.Value)
i += 1
'the match contains a tag
ElseIf match.Value.Length > 1 Then
content.Append(match.Value)
End If
Next
Return Regex.Replace(content.ToString(), emptytags, String.Empty)
End Function
しかし、いつもうまくいかなかった