tags:

views:

46

answers:

2

Hi all,

I'm currently developing a script that takes a message, splits it apart every 100 characters or so, and sends each part.

However, my original string has "\n" lines in it, and this is causing an issue with my preg_split, causing it to split pre-maturely (e.g., before 100 characters).

Here's what I am currently working with:

$sMessage = "Msg from John Smith \n".
            "SUBJ: Hello! \n".
            "This is the bulk of the message and can be well over 200 or 300 characters long. \n".
            "To reply, type R 131, then ur msg.";


 $split = preg_split('/(.{0,100})\s/',
                $sMessage,
                0,
                PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  array_shift($split); 

  $count = count($split);
  foreach ($split as $key => $message) {
  $part = sprintf("(%d/%d) %s", $key+1, $count, $message);
   echo $part;
   echo "<br>";
  }

Now, with this, I've noticed 3 things:

1) The first part of the message ("Msg from John Smith") does not even get included in the array.

2) The new lines (\n) seem to cut the string early.

3) Oddly enough, with the last line of the message ("To reply" etc...) it cuts off the last word ("msg.") and adds that into a new line, no matter what the sentence may read.

Any help on this would be great!

+2  A: 

You are actually trying to reimplement the function wordwrap(). I think the call that does the job you need would look like this:

$array = explode("\n", wordwrap($string, 100, "\n", true));
soulmerge
Check out my comment above.
Dodinas
You're correct, forgot that it returns a string. But converting that to an array is easy. Thie function is `explode()`: http://us2.php.net/manual/en/function.explode.php
soulmerge
A: 

my original string has "\n" lines in it

Use the PCRE_DOTALL modifier to allow ‘.’ to match newlines.

Chunking a string into an array of fixed-length strings can more easily be done using str_split. As soulmerge suggests, wordwrap is probably better if that's what you're really trying to do. You can use explode to split a string out to an array afterwards.

Avoid resorting to regex where string processing functions are available. (And PHP has a lot.)

bobince