ivandrofly

HtmlUtil.FIxInvalidTag: Better solution to handle empty tags

Feb 13th, 2025
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1.         [TestMethod]
  2.         [DataRow("Foo<i></i>bar")]
  3.         [DataRow("Foo<i>    </i>bar")]
  4.         [DataRow("<i>Foo</i>    <i>bar</i>", "<i>Foobar</i>")]
  5.         // [DataRow("Foo<b>    </b>bar")]
  6.         // [DataRow("Foo<u>    </u>bar")]
  7.         // [DataRow("Foo<font color=\"#808080\"> </font>bar")]
  8.         // [DataRow("Foo<font color=\"#808080\"></font>bar")]
  9.         public void FixInvalidItalicEmptyTagTest(string input, string expected = "Foobar")
  10.         {
  11.             Assert.AreEqual(expected, HtmlUtil.FixInvalidItalicTags(input));
  12.         }
  13.  
  14.  
  15. ...............
  16.  
  17.  
  18. // <i>foo</i><i>bar</i> => <i>foobar</i>
  19.             // <i>foo</i> <i>bar</i> => <i>foo bar</i>
  20.             // text = text.Replace("</i><i>", string.Empty); (handle bellow)
  21.             text = text.Replace("</i> <i>", " ");
  22.  
  23.             var l = 0;
  24.             var closeCount = 0;
  25.             for (var r = 0; r < text.Length; r++)
  26.             {
  27.                 if (text[r] == '<' && text[l] != '<')
  28.                 {
  29.                     l = r;
  30.                 }
  31.                 else if (text[r] == '>' && text[l] == '<' && ++closeCount == 2)
  32.                 {
  33.                     var st = new StrippableText(text.Substring(l, r - l + 1));
  34.  
  35.                     // no formattable text in between the tags e.g: ...<i> </i>...
  36.                     if (string.IsNullOrWhiteSpace(st.StrippedText) &&
  37.                         st.OriginalText.EndsWith("<i>", StringComparison.Ordinal) &&
  38.                         st.OriginalText.StartsWith("</i>", StringComparison.Ordinal))
  39.                     {
  40.                         text = text.Remove(l, r - l + 1);
  41.                         r = l - 1;
  42.                         closeCount = 0;
  43.                     }
  44.                     else
  45.                     {
  46.                         // start counting from the last found tag
  47.                         // For example in "<i>Foo</i>    <i>bar</i>" Skip first tag
  48.                         l = text.LastIndexOf('<', r - 1);
  49.                         closeCount -= 1;
  50.                     }
  51.                 }
  52.             }
  53.  
  54.             return preTags + text;
  55.         }
Tags: SubtitleEdit
Add Comment
Please, Sign In to add comment