PHP explodes then double loop
I'm trying to split the string to stay under the 70 character limit ... however, when I do this, my loop just stops when it receives the first 70 characters and it doesn't try to execute the 2nd set. The reason I go this route and not use str_split
is to keep all the words so that I don't send half word messages. If the 2nd split is less than 70 characters please submit it ... any help with this is greatly appreciated.
$message="A new powerful earthquake convulsed the traumatized nation of Nepal on Tuesday, leveling buildings already damaged by the devastating quake that killed thousands of people less than three weeks ago."
$msg = explode(' ',$message);
foreach($msg as $key) {
$keylen = strlen($key);
$msglen = $msglen + $keylen;
if($msglen<70) {
$msgs .=$key." ";
// $agi->verbose("$msgs");
} else {
$params = array(
'src' => '18009993355',
'dst' => $callerid,
'text' => $msgs,
'type' => 'sms',
);
// $agi->verbose("sending: $msgs");
$response = $p->send_message($params);
$msgs = "";
$msglen = 0;
}
}
+3
source to share
2 answers
<?php
$message = "A new powerful earthquake convulsed the traumatized nation of Nepal on Tuesday, leveling buildings already damaged by the devastating quake that killed thousands of people less than three weeks ago.";
define ("MAX_PACKET_SIZE", 70);
$msg = explode (' ',$message);
$indexes = array (0);
$actualSize = 0 ;
for ($i=0 ; $i<count($msg) ; $i++) {
if ($actualSize + strlen ($msg[$i]) <= MAX_PACKET_SIZE ) {
$actualSize += strlen ($msg[$i]);
if (($i+1) < count($msg)) {
$actualSize++;
}
}else {
$indexes[] = $i;
$actualSize = 0 ;
}
}
$indexes[] = count ($msg);
for ($i=1 ; $i<count($indexes) ; $i++) {
$temp = array_extract ($msg, $indexes[$i-1], $indexes[$i]);
var_dump(implode (' ', $temp));
$params = array ('src' => '18009993355',
'dst' => $callerid,
'text' => implode (' ', $temp) ,
'type' => 'sms');
// $agi->verbose("sending: $msgs");
$response = $p->send_message($params);
}
function array_extract ($array, $start, $stop) {
$temp = array();
for ($i=$start ; $i<$stop ; $i++) {
$temp[] = $array[$i];
}
return $temp;
}
+2
source to share