Code Snippet - Extracting Meta Descriptions
On Saturday I spent some time working on my new website, which will one day be finished, and decided that it needed to extract a Meta Description from the Database for each page, to help provide search engines with suitable descriptions. Now the easiest way is to just have a field in your database and admin / cms system for this, however when you don't want a specific description from the database it would be useful for the page to instead pull 20 words from the body text. So i decided to write myself a small function that would strip out any HTML and return a specified number of words from a string input. I have included it below with a possible use, in this case Meta Description.
public string extractWords(string input, int wordNum) { string output = ""; int i; int maxi; input = Regex.Replace(input, @"<[^>]*>", string.Empty); Array words = input.Split(new char[] {' '}); if (words.Length < maxi =" words.Length;" maxi =" wordNum;" i =" 0;" output="" return="">Example
if (pageContent[0]["metadescription"].ToString() != ""){ stringDescription = pageContent[0]["metadescription"].ToString(); } else{ stringDescription = extractWords(pageContent[0]["body"].ToString(), 20); }
No comments:
Post a Comment