Zend twitter view helper for better user experience

Displaying tweets on a website in the same manner that twitter displays them is a nice user friendly feature to have. Shown bellow is the source for a zend twitter view helper. It should be placed in the “views/helpers” directory in your project in a file named Twitter.php.

<?php
class Zend_View_Helper_Twitter extends Zend_View_Helper_Abstract
{
	public function twitter()
	{
		return $this;
	}

	public function linkifyUsernames($tweet)
	{
		return preg_replace("/@(\w+)/i", "<a href=\"http://twitter.com/$1\" target=\"_blank\">$0</a>", $tweet);
	}

	public function linkifyHashTags($tweet)
	{
		return preg_replace("/#(\w+)/i", "<a href=\"http://twitter.com/#!/search/%23$1\" target=\"_blank\">$0</a>", $tweet);
	}

	public function linkify($tweet)
	{
		$tweet = $this->linkifyUsernames($tweet);
		$tweet = $this->linkifyHashTags($tweet);

		return $tweet;
	}
}

Usage

After you create the file this zend twitter view helper can be used from your view script by calling the twitter() method and then using either linkifyUsernames(), linkifyHashTags() or just linkify() to linkify both usernames and hashtags.

The regular expressions will convert #anystring to

<a href="http://twitter.com/#!/search/#anystring" target="blank">#anystring</a>

and @anyone to

<a href="http://twitter.com/@anyone" target="blank">@anyone</a>

Example

In a view script:

<?php echo $this->twitter()->linkify("Lorem @ipsum dolor #sit amet, consetetur sadipscing @elitr, sed diam nonumyeirmod #tempor invidunt ut #labore et dolore magna"); ?>

will output:
Lorem @ipsum dolor #sit amet, consetetur sadipscing @elitr, sed diam nonumyeirmod #tempor invidunt ut #labore et dolore magna

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 1 = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>