views:

335

answers:

4

I'm having trouble with the logic of taking a paragraph of text and splitting it on words/sentences to send out in multiple text messages. Each text message can only have up to 160 characters. I want to cleanly break a paragraph up.

Here is the solution (thanks Leventix!):

public static function splitStringAtWordsUpToCharacterLimit($string, $characterLimit) {
    return explode("\n", wordwrap($string, $characterLimit));
}
+5  A: 

You can use wordwrap, then explode by newlines.

Leventix
I bow down to your answer :). I do love this site, It's making me a better programmer by answering these questions, and then by finding out peoples solutions to the problems they've faced. Very cool Leventix!
Mark Tomlin
A: 

Why would you ever need to use a regular expression here!?

All that you would have to do is split the string into however many pieces of text messages. so you would do something like (I can't remember exact syntax, my PHP is rusty) length($string)/$charmax and then just do substring that many times into an array and return that array

Earlz
He's trying to avoid breaking in the middle of a word, I think.
John Booty
A: 
<?php
 $string = str_repeat('Welcome to StackOverFlow, Heres Your Example Code!', 6);

 print_r(str_split($string, 160));

 # You could also Alias the function.
 function textMsgSplit($string, $splitLen = 160) {
  return str_split($string, $splitLen);
 }
?>
Mark Tomlin
+2  A: 

This is the function I use,

function sms_chunk_split($msg) {
   $msg = preg_replace('/[\r\n]+/', ' ', $msg);
   $chunks = wordwrap($msg, 160, '\n');
   return explode('\n', $chunks);
}

It splits a long SMS message into an array of 160-byte chunks, splitting at word boundaries.

ZZ Coder