【问题标题】:How to remove double html <strong> tag from string in C#如何从 C# 中的字符串中删除双 html <strong> 标签
【发布时间】:2011-11-08 09:32:37
【问题描述】:

我想在我的 ASP.NET MVC 3 网站上进行搜索,所以对于搜索我必须找到匹配的模式,并且用粗体字替换匹配的部分(我使用那个 html &lt;strong&gt; 标签) .

所以我的控制器中有这个

        string[] words=content.Split(' ');
        foreach (Thread thread in context.Threads)
        {
            foreach (string word in words)
            {
                if (thread.Title.ToLower().Contains(word.ToLower()))
                {
                    thread.Title=Regex.Replace(thread.Title,word,String.Format("<strong>{0}</strong>","$0"),RegexOptions.IgnoreCase);
                }
            }

         }

所以,如果我搜索new thread a,它会找到像New thrEAd 这样的线程。

但是在 html 中它使我的字符串变成那样

<strong>New</strong> <strong>thrE<strong>A</strong>d</strong>

所以我想从 a 中删除 strong 标签,因为它是双粗体... 我该怎么做?

如果你有有趣的方法来进行我的搜索,我也很高兴听到你的建议。

【问题讨论】:

  • 很抱歉这个问题,但我需要了解这一点。所以你有一个单词列表,如果它们匹配,它们应该用 括起来。是这个问题吗?

标签: c# html regex asp.net-mvc-3 search


【解决方案1】:

你可以清理你的搜索词,检查它们都不包含任何其他词:

var cleanWords = words.Where(w => !words.Any(w2 => w2.Contains(w));

【讨论】:

  • 这不是一个解决方案...如果我有“新线程”怎么办...它不会使粗体“a”,因为“线程”包含“a”))
【解决方案2】:

试试这个:

IEnumerable<string> enumerableWords = content.Split(' ').Distinct();
string[] words = enumerableWords.ToArray();
foreach (Thread thread in context.Threads) {
    string result = thread.Title;
    foreach (string word in words) {
        result = Regex.Replace(result, String.Format(@"\b{0}\b", word), String.Format(@"<strong>{0}</strong>", word), RegexOptions.IgnoreCase);
    }
    thread.Title = result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2019-03-31
    • 2021-02-05
    • 2019-01-06
    相关资源
    最近更新 更多