Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Extract Search Keyword from Google, Yahoo and other search URL in C#

Every web site has major percentage of referral traffic from Google, so it is necessary to understand what keyword do users search and reach the website.
The following code extracts the search keyword from Google, Yahoo, etc

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Text;
  5. using System.Web;
  6. using System.Text.RegularExpressions;
  7. namespace forgetcode
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. Uri referrer = HttpContext.Current.Request.UrlReferrer;
  14. if (referrer != null)
  15. {
  16. string original = referrer.OriginalString.ToLower();
  17. string keyword = GetKeyword(original);
  18. Console.WriteLine("Visitor Searched For "+keyword);
  19. }
  20. }
  21. private static string GetKeyword(string strU)
  22. {
  23. Regex regKeyword = new Regex("(p|q)=(?<keyword>.*?)&", RegexOptions.IgnoreCase | RegexOptions.Multiline);
  24. Regex regSnippet = new Regex("forgetcode.com.*%2F(?<id>\\d+)%2F", RegexOptions.IgnoreCase | RegexOptions.Multiline);
  25. Match match = regKeyword.Match(strU);
  26. string keyword = match.Groups["keyword"].ToString();
  27. // Get the decoded URL
  28. string result = HttpUtility.UrlDecode(keyword);
  29. // Get the HTML representation
  30. result = HttpUtility.HtmlEncode(result);
  31. return result;
  32. }
  33. }
  34. }


Note : This code / any code will not work if the user is logged in, Google encrypts search URL when the user is logged in.