tyler jones
07-17-2009, 02:48 PM
I have a page that displays a block of text and on this page I'm highlighting search terms that a user used to find the page. I've run into a problem where the search term is showing up in a url inside an href tag so when I surround the term with a span tag it breaks the href tag. Is there a way to search for instances of the term to highlight outside of links? Here's the code I'm using now. Thanks.
public static string Highlight(string textToHighlight, string keywords, string highlightClass)
{
if (keywords.Length > 0)
{
const string pattern = @"(and)|(\s{1,}or)|(\"")|(\')";
string[] stmp =
Regex.Replace(keywords.Replace("(", string.Empty).Replace(")", string.Empty), pattern, string.Empty,
RegexOptions.IgnoreCase).Split(' ');
Regex r;
foreach (string s in stmp)
{
if (s.Trim().Length <= 2) continue;
r = new Regex(s, RegexOptions.IgnoreCase);
foreach (Match m in r.Matches(textToHighlight))
textToHighlight = Regex.Replace(textToHighlight, m.Value,
"<span class=\"" + highlightClass + "\">" + m.Value +
"</span>");
}
}
return textToHighlight;
}
public static string Highlight(string textToHighlight, string keywords, string highlightClass)
{
if (keywords.Length > 0)
{
const string pattern = @"(and)|(\s{1,}or)|(\"")|(\')";
string[] stmp =
Regex.Replace(keywords.Replace("(", string.Empty).Replace(")", string.Empty), pattern, string.Empty,
RegexOptions.IgnoreCase).Split(' ');
Regex r;
foreach (string s in stmp)
{
if (s.Trim().Length <= 2) continue;
r = new Regex(s, RegexOptions.IgnoreCase);
foreach (Match m in r.Matches(textToHighlight))
textToHighlight = Regex.Replace(textToHighlight, m.Value,
"<span class=\"" + highlightClass + "\">" + m.Value +
"</span>");
}
}
return textToHighlight;
}