Posted By

s0l1dsnak3123 on 04/13/10


Tagged

array String text split characters twitter 140


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

dantreacy


Split text up into 140 char array for twitter


 / Published in: PHP
 

splittochunks splits the string up into an array with elements containing 140 characters or less. This enables you to keep words intact when sending automated twitter messages.

$to is needed in order to subtract from 140 the amount of characters allowed. This is important because a long username could create problems with messages being too long. This could be done pragmatically, and would be relatively simple to do, but was not needed in my case and so was not implemented.

$text contains a string containing any amount of characters - including under 140.

$message is an array which gives the message minus the username at the front.

  1. /* split_to_chunks by John Hamelink 2010. This code is in the PUBLIC DOMAIN. */
  2.  
  3. function split_to_chunks($to,$text){
  4. $total_length = (140 - strlen($to));
  5. $text_arr = explode(" ",$text);
  6. $i=0;
  7. $message[0]="";
  8. foreach ($text_arr as $word){
  9. if ( strlen($message[$i] . $word . ' ') <= $total_length ){
  10. if ($text_arr[count($text_arr)-1] == $word){
  11. $message[$i] .= $word;
  12. } else {
  13. $message[$i] .= $word . ' ';
  14. }
  15. } else {
  16. $i++;
  17. if ($text_arr[count($text_arr)-1] == $word){
  18. $message[$i] = $word;
  19. } else {
  20. $message[$i] = $word . ' ';
  21. }
  22. }
  23. }
  24. return $message;
  25. }

Report this snippet  

You need to login to post a comment.