PDA

View Full Version : need help with regular expression


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;
}

scottk
07-18-2009, 02:22 PM
How are you calling the function? Are you capturing the raw html output before it goes downstream and feeding it to that method?

You can do the highlighting client side which is what I typically see: http://eriwen.com/javascript/highlight-search-results-with-js/

I'm always afraid to modify my pages based on search criteria because then a search engine might think you are trying to serve different content to a user based on their referrer which is against every SERP's acceptable use policy. Just something to consider....