Twitter
expose API to show tweets on your site. But tweet feed return your tweet as
normal texts (i.e. all your links are not there), and if you show these tweet
feeds on your site, then it’ll be shown as plain text.
So you
want your tweet to be shown same as it is live on twitter, i.e. text along with
all the links?
To do
this we can use Regex (Regular Expression). Regex is very handy to solve our problems.
What need
to be replaced?
·
Links
starting with http://
·
Links
starting with www
·
Twitter
username links, i.e. @ sandeepkumar17
·
Twitter
hash tag links, i.e. #India
So I have created one method to format the
tweet text, just pass the tweet text to this method and it’ll return your tweet with
all the links.
//use for namespace for regular expression.
using
System.Text.RegularExpressions;
private static String GetFormattedTweet(string tweetText)
{
var httpLinks = @"(^|[\n ])([\w]+?://[\w]+[^ \n\r\t< ]*)";
var wwwLinks = @"(^|[\n ])((www|ftp)\.[^ \t\n\r< ]*)";
var twitterName = @"@(\w+)";
var twitterTag = @"#(\w+)";
tweetText = Regex.Replace(tweetText,
httpLinks,
" <a href=\"$2\"
target=\"_blank\">$2</a>");
tweetText = Regex.Replace(tweetText,
wwwLinks,
"
<a href=\"http://$2\"
target=\"_blank\">$2</a>");
tweetText = Regex.Replace(tweetText,
twitterName,
"<a href=\"http://www.twitter.com/$1\"
target=\"_blank\">@$1</a>");
tweetText = Regex.Replace(tweetText,
twitterTag,
"<a
href=\"http://search.twitter.com/search?q=$1\"
target=\"_blank\">#$1</a>");
return tweetText;
}
|
That’s
it, and tweet is now fully formatted J
Comments
Post a Comment