My client is looking for a way to send a text message to the Twilio PHP script I programmed and then have it rebroadcast to personnel in the field. That's the easy part, simply check to see if the incoming number is authorized, pull the personnel details from MySQL, and distribute.
Here's the tricky part - the people using this may be long winded and their phones allow them to enter more than 160 characters. Assuming that Twilio can receive >160 characters (I know it cannot send >160), I need to break this long message (string) up into chunks that fall under 160 characters.
Here is the script that I came up with to do so, it works great but I would like for it to end on a complete word, rather than simply the next character after it is split. Funny side story, when you forget to enter the length at which to split the string, you receive 171 or so one character text messages! :P
<?php
$string = "Ulysses, Ulysses - Soaring through all the galaxies. In search of Earth, flying in to the night. Ulysses, Ulysses - Fighting evil and tyranny, with all his power, and with all of his might. Ulysses - no-one else can do the things you do. Ulysses - like a bolt of thunder from the blue. Ulysses - always fighting all the evil forces bringing peace and justice to all.";
$arr = str_split($string, 155); //Factoring in the message count
$num = count($arr); //See how many chunks there are
$i = 1; //Set interval to 1
foreach ($arr as $value) {
if ($num > 1) {
echo "($i/$num) $value<br/>"; //(x/x) Message...
$i++;
} else {
echo $value; //Message...
}
}
?>
Many thanks
CORRECTION Sorry, major oversight on my part - I posted the development script to play with the strings rather than the live script that sends the actual SMS after "the incident." I need to be able to iterate over the chunks to send each out as its own SMS after it is split, as the above will do.. just ending on a complete word. The SMS would be sent in the foreach loop.
I don't get why all the over complicated answers when you can just use:
$chunks = explode("||||",wordwrap($message,155,"||||",false));
$total = count($chunks);
foreach($chunks as $page => $chunk)
{
$message = sprintf("(%d/%d) %s",$page+1,$total,$chunk);
}
This would produce something like:
(1/3) Primis facilis apeirian vis ne. Idque ignota est ei. Ut sonet indoctum nam, ius ea illum fabellas. Pri delicata percipitur ad, munere ponderum rationibus.
Online Example: http://codepad.org/DTOpbPIJ Updated
Try wordwrap: http://www.php.net/manual/en/function.wordwrap.php
<?php
$words = "this is a long sentence that needs splitting";
foreach(explode("\n", wordwrap($words, 10, "\n")) as $s) {
echo $s . "\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With