Alex Rivera | Logout

Formatting Twitter text (TweetText) with C#

Asked 2009-07-27T01:55:21.860
12

Is there a better way to format text from Twitter to link the hyperlinks, username and hashtags? What I have is working but I know this could be done better. I am interested in alternative techniques. I am setting this up as a HTML Helper for ASP.NET MVC.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Acme.Mvc.Extensions
{

    public static class MvcExtensions
    {
        const string ScreenNamePattern = @"@([A-Za-z0-9\-_&;]+)";
        const string HashTagPattern = @"#([A-Za-z0-9\-_&;]+)";
        const string HyperLinkPattern = @"(http://\S+)\s?";

        public static string TweetText(this HtmlHelper helper, string text)
        {
            return FormatTweetText(text);
        }

        public static string FormatTweetText(string text)
        {
            string result = text;

            if (result.Contains("http://"))
            {
                var links = new List<string>();
                foreach (Match match in Regex.Matches(result, HyperLinkPattern))
                {
                    var url = match.Groups[1].Value;
                    if (!links.Contains(url))
                    {
                        links.Add(url);
                        result = result.Replace(url, String.Format("<a href=\"{0}\">{0}</a>", url));
                    }
                }
            }

            if (result.Contains("@"))
            {
                var names = new List<string>();
                foreach (Match match in Regex.Matches(result, ScreenNamePattern))
                {
                    var screenName = match.Groups[1].Value;
                    if (!names.Contains(screenName))
                    {
                        names.Add(screenName);
                        result = result.Replace("@" + screenName,
                           String.Format("<a href=\"http://twitter.com/{0}\">@{0}
Edit
Report

1 Answer

0

I created helper method to shorten text to 140 chars with url included. You can set share length to 0 to exclude url from tweet.

 public static string FormatTwitterText(this string text, string shareurl)
    {
        if (string.IsNullOrEmpty(text))
            return string.Empty;

        string finaltext = string.Empty;
        string sharepath = string.Format("http://url.com/{0}", shareurl);

        //list of all words, trimmed and new space removed
        List<string> textlist = text.Split(' ').Select(txt => Regex.Replace(txt, @"\n", "").Trim())
                              .Where(formatedtxt => !string.IsNullOrEmpty(formatedtxt))
                              .ToList();

        int extraChars = 3; //to account for the two dots ".."
        int finalLength = 140 - sharepath.Length - extraChars;
        int runningLengthCount = 0;
        int collectionCount = textlist.Count;
        int count = 0;
        foreach (string eachwordformated in textlist
                .Select(eachword => string.Format("{0} ", eachword)))
        {
            count++;
            int textlength = eachwordformated.Length;
            runningLengthCount += textlength;
            int nextcount = count + 1;

            var nextTextlength = nextcount < collectionCount ? 
                                             textlist[nextcount].Length : 
                                             0;

            if (runningLengthCount + nextTextlength < finalLength)
                finaltext += eachwordformated;
        }

        return runningLengthCount > finalLength ? finaltext.Trim() + ".." : finaltext.Trim();
    }
answered 2013-04-27T21:02:51.717

Your Answer