Blog Post RSS ?

Blogs » .NET » Working with HTML markup
 

Working with HTML markup

by miseldine

This happened to me recently. I needed a way of highlighting keywords in a chunk of HTML for when users visited the site through Google. In this way, you can help your users locate the information they’ve searched for in Google quickly.

However, a simple string.Replace function wouldn’t cut the mustard. Obviously, it would also replace any mention of a keyword in the HTML markup too, and so would kill links or images.

For example, take the keyword “sitepoint” and I wish to replace it with some HTML “sitepoint“. If my image name had “sitepoint” in it, I’d end up with sitepoint.jpg”>. Not what I want.

So, I hacked together a little function to first remove all the HTML tags in a string, and then replace them once the replacement has been made. I hope it is of some use, fellow readers:

private string highlightText(string text, string keyword, string highlightColour) { //ok strip the tags, but keep them safe System.Collections.ArrayList a = new System.Collections.ArrayList(); string temp = text; //ok, find an < while (temp.IndexOf("<") != -1) { int start = temp.IndexOf("<"); int end = temp.IndexOf(">"); //ok. remove a.Add(temp.Substring(start,end-start+1)); temp = temp.Substring(0,start)+"¬"+temp.Substring(end+1); } //ok. string has no html now string body = temp.Replace(keyword,""+keyword+""); string keyUp = keyword.Substring(0,1).ToUpper()+keyword.Substring(1,keyword.Length-1); if (keyUp != keyword) { body = body.Replace(keyUp,""+keyUp+""); } //right. re-insert the tags while (body.IndexOf("¬") != -1) { int pos = body.IndexOf("¬"); body = body.Remove(pos,1); body = body.Insert(pos,(string)a[0]); a.RemoveAt(0); } return body; }

It’s not optmised, and it isn’t pretty, but tinker and expand upon it at your will :)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. W3C Markup Validation Service adds experimental HTML5 support A few days ago, the W3C added experimental support for...
  2. Add Semantic Richness To Your Markup With (RDF) Ease Meitar takes another look at bleeding edge Semantic Web technologies...
  3. The 5 Most Under-Used HTML Tags It is easy to forget some of the lesser-known HTML...
  4. HTML 4 Considered Harmful In this post, a frustrated James once again rallies to...
  5. How to Use PHP Namespaces, Part 3: Keywords and Autoloading In the final part of his series explaining PHP namespaces,...

This post has 5 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...