2014-03-27 158 views
0

我想突出显示结果中的搜索项。一般来说,它基于SO上的代码here工作正常。我的问题是它用搜索词替换子字符串,即在这个例子中,它将用“爱”(不可接受)代替“LOVE”。所以我想我可能想要找到子字符串开头的索引,做一个INSERT开始的<范围>标记,并在子字符串的末尾做相似处理。由于yafs可能相当长,我还认为我需要将stringbuilder集成到此。这是可行的,还是有更好的方法?一如既往,预先感谢您的建议。插入搜索项子索引索引

string yafs = "Looking for LOVE in all the wrong places..."; 
string searchTerm = "love"; 

yafs = yafs.ReplaceInsensitive(searchTerm, "<span style='background-color: #FFFF00'>" 
+ searchTerm + "</span>"); 
+0

不是所有这些网站使用JavaScript来做到这一点在客户端? –

+0

在你做替换之前你的字符串已经是HTML吗?如果是这样,小心简单的替换。如果有人正在搜索“html”(或其他html标签),您的完整网站将被打破。 –

+0

thanx的提示。在这种情况下,它是预先格式化的文本,不涉及html。 – Darkloki

回答

1
如何

一下:

public static string ReplaceInsensitive(string yafs, string searchTerm) { 
    return Regex.Replace(yafs, "(" + searchTerm + ")", "<span style='background-color: #FFFF00'>$1</span>", RegexOptions.IgnoreCase); 
} 

更新:

public static string ReplaceInsensitive(string yafs, string searchTerm) { 
    return Regex.Replace(yafs, 
     "(" + Regex.Escape(searchTerm) + ")", 
     "<span style='background-color: #FFFF00'>$1</span>", 
     RegexOptions.IgnoreCase); 
} 
+1

如果有人在搜索'。*',一切都消失了? –

+0

感谢所有人。其他选项可能会工作,但这看起来最简单,迄今为止它测试的很好。 – Darkloki

+0

哎呀,在这种情况下必须逃脱...对不起 –

1

请问你需要什么:

static void Main(string[] args) 
{ 
    string yafs = "Looking for LOVE in all the wrong love places..."; 
    string searchTerm = "LOVE"; 

    Console.Write(ReplaceInsensitive(yafs, searchTerm)); 
    Console.Read(); 
} 

private static string ReplaceInsensitive(string yafs, string searchTerm) 
{ 
    StringBuilder sb = new StringBuilder(); 
    foreach (string word in yafs.Split(' ')) 
    { 
     string tempStr = word; 
     if (word.ToUpper() == searchTerm.ToUpper()) 
     { 
      tempStr = word.Insert(0, "<span style='background-color: #FFFF00'>"); 
      int len = tempStr.Length; 
      tempStr = tempStr.Insert(len, "</span>"); 
     } 

     sb.AppendFormat("{0} ", tempStr); 
    } 

    return sb.ToString(); 
} 

给出:

寻找<跨度风格= '背景色:#FFFF00' 在> LOVE </SPAN>所有错<跨度风格= '背景色:#FFFF00'>爱</span>的地方......

+0

这只会取代搜索词的第一次出现。 –

+0

道歉,没有意识到会有字符串中的单词的多个实例。更新。 – DGibbs

0

检查这个代码

private static string ReplaceInsensitive(string text, string oldtext,string newtext) 
    { 
     int indexof = text.IndexOf(oldtext,0,StringComparison.InvariantCultureIgnoreCase); 
     while (indexof != -1) 
     { 
      text = text.Remove(indexof, oldtext.Length); 
      text = text.Insert(indexof, newtext); 


      indexof = text.IndexOf(oldtext, indexof + newtext.Length ,StringComparison.InvariantCultureIgnoreCase); 
     } 

     return text; 
    }