現在用戶搜索的是280,這時候就要把上面這個字符串變爲:
str="<span >這個是測試<a href='http://www.lmwlove.com/ac/ID280' ><label style='color:red' >280</label ></a >這裏是其它測試</span >",需要注意的是,我的href中也有280這個關鍵字,但這個280是不能夠被替換的。
csdn上高人的解決方法,都複製如下,有些並不能完全解決這個問題,但我覺的還是有學習的價值,也粘貼如下,各回複用--隔開
-------------------------------------------------------------
{
title = title.Replace(redkey, "<font color='#ff0000' >" + redkey + "</font >");
return title;
}
這個是用C#實現的
-------------------------------------------------------------
<head runat="server" >
</head >
<body >
<form id="form1" runat="server" >
<div >
<a href='#?id=280' id="a1" >280</a >
<script > document.getElementById("a1").innerHTML=document.getElementById("a1").innerHTML.replace("280","<font color='red' >280</font >");
</script >
</div >
</form >
</body >
</html >
這個是用js實現的
-------------------------------------------------------------
{
string reValue = tmpStr;
string xingcheng = @"([a-zA-Z]{6})";
reValue = Regex.Replace(reValue, xingcheng, "<font color=yellow >$1</font >");
}
這個是在C#中調用js實現
-------------------------------------------------------------
string r = @"( >[ \s\S]*)(280)([ \s\S]*<)";
string v = Regex.Replace(s, r, "$1<font color=red >$2</font >$3");
Response.Write(v);
這個是使用正則實現
-------------------------------------------------------------
<head >
<title >IE Range Example</title >
<script type="text/javascript" >
function useRanges() {
var oRange = document.body.createTextRange();
var oP1 = document.getElementById("p1");
oRange.findText("Hello");
oRange.pasteHTML("<em >Howdy</em >");
}
</script >
</head >
<body ><p id="p1" ><b >Hello</b > World</p >
<input type="button" value="Use Ranges" οnclick="useRanges()" / >
<p ><strong >Note:</strong > This example uses Internet Explorer ranges and will only work on Internet Explorer.</p >
</body >
</html >
這個是使用jquery實現
-------------------------------------------------------------
/// ----分析keyword,空格分離
{
word = Regex.Replace(word, @"(\"")|(\()|(\))|(\+)|(\|)|(-)|(“)|(”)|(()|())|(+)|(-)|(\\)|(\*)|(\<)|(\ >)|( )", " ");
/*word = word.Replace("(", " ");
word = word.Replace(")", " ");
word = word.Replace("-", " ");
word = word.Replace("|", " ");*/
word = Regex.Replace(word, @"\s+", " ");
return word.Trim();
}
public static string HLTextDisplay(string strWord, string strSource)
{
strSource = System.Text.RegularExpressions.Regex.Replace(strSource, @"<\w+[^< >]* >|<\/\w+[^< >]* >", "");
strSource = System.Text.RegularExpressions.Regex.Replace(strSource, "\r\n", @"<br >");
if (strWord==null || strWord.Length==0) return strSource;
strWord = HLSearchWords(strWord);
string strTemp=strSource;
strWord = "(" + Regex.Replace(strWord, @"\s+", ")|(") + ")";
strTemp = Regex.Replace(strTemp, strWord, "<font color=color:#00c >$&</font >", RegexOptions.IgnoreCase);
return strTemp;
}
這個是使用C#加正則實現
高手們寫出了這麼多的實現方法,總有一個是適合我們的吧,我們要學習的,不僅僅是代碼,還有解題思路。高手們的解題思路已經貼出來,供大家參考吧。