Clone
5
Twitter Tweet Parser
Derek Jones edited this page 2012-07-05 13:58:23 -07:00

Introduction

Twitter Apps are all the rage these days. When displaying a tweet, there is actually a lot of information that comes back from twitter's servers, and It's always plain text. This helper simply parses the tweet, and converts the plain-text into marked up embedable code.



if (!function_exists('parse_tweet'))
    {
        function parse_tweet($tweet)
        {
            $search = array('|(http://[^ ]+)|', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i');
            $replace = array('<a href="$1">$1</a>', '$1<a href="http://twitter.com/$2">@$2</a>', '$1<a href="http://search.twitter.com/search?q=#$2">#$2</a>');
            $tweet = preg_replace($search, $replace, $tweet);
            
            return $tweet;
        }
    } 


Usage

Simply pass this helper a tweet, and it returns the text with hyperlinks embedded.


$parsed_tweet = parse_tweet($tweet_text);