Split text up into 140 char array for Twitter

Submitted by:Jhon Jhon

Date added:24 July, 2012

Category:PHP

If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.

Tags: php function , twitter

Code Snippet:

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;
}
 
 

Comments