Split text up into 140 char array for Twitter

Are you a Twitter user? If yes, you probably know how easy it is to interact with the service using the API. Here’s a nice function to split a text into 140 characters (or less) chunks.

function split_to_chunks($to,$text){
	$total_length = (140 - strlen($to));
	$text_arr = explode(" ",$text);
	$i=0;
	$message[0]="";
	foreach ($text_arr as $word){
		if ( strlen($message[$i] . $word . ' ') <= $total_length ){
			if ($text_arr[count($text_arr)-1] == $word){
				$message[$i] .= $word;
			} else {
				$message[$i] .= $word . ' ';
			}
		} else {
			$i++;
			if ($text_arr[count($text_arr)-1] == $word){
				$message[$i] = $word;
			} else {
				$message[$i] = $word . ' ';
			}
		}
	}
	return $message;
}

Usage

$chunks = split_to_chunks(10,"My very long phrase to split");

One Trackback

  1. [...] This post was mentioned on Twitter by Jean-Baptiste Jung, phpsnippets. phpsnippets said: PHP snippet: Split text up into 140 char array for Twitter http://bit.ly/bMTTjS #twitter #php [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

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>