tags:

views:

179

answers:

3

Hello all,

I'm starting to work on a small script that takes a string, counts the number of characters, then, based on the number of characters, splits/breaks the string apart and sends/emails 110 characters at a time.

What would be the proper logic/PHP to use to:

1) Count the number of characters in the string
2) Preface each message with (1/3) (2/3) (3/3), etc...
3) And only send 110 characters at a time.

I know I'd probably have to use strlen to count the characters, and some type of loop to loop through, but I'm not quite sure how to go about it.

Thanks!

A: 

use str_split() and iterate over the resulting array.

Simon Groenewolt
A: 

From the top of my head, should work as is, but doesn't have to. Logic is ok though.

foreach ($messages as $msg) {

  $len = strlen($msg);

  if ($len > 110) {
    $parts = ceil($len / 100);
    for ($i = 1; $i <= $parts; $i++) {
      $part = $i . '/' . $parts . ' ' . substr($msg, 0, 110);
      $msg = substr($msg, 109);
      your_sending_func($part);
    }

  } else {
    your_sending_func($msg);
  }

}
code_burgar
+1  A: 

You could use str_split, if you're not concerned with where you break the strings.

Else, if you are concerned with this (and want to, say, split only on a whitespace), you could do something like:

// $str is the string you want to chop up.
$split = preg_split('/(.{0,110})\s/',
                    $str,
                    0,
                    PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

With this array you could then simply do:

$count = count($split);
foreach ($split as $key => $message) {
    $part = sprintf("(%d/%d) %s", $key+1, $count, $message);
    // $part is now one of your messages;
    // do what you wish with it here.
}
Sebastian P.
Thanks, Sebastian. I like your method, but it seems with the preg_split, no matter how many characters I put (over 110), it creates an array of only 2, when (in most cases) it should be 3 or more. Any ideas?
Dodinas
My bad; fixed up the regular expression to work. Should do the desired job now.
Sebastian P.
Thanks, this was a great help!
Dodinas