PHP爆炸然后双循环

时间:2015-05-12 08:42:41

标签: php foreach explode

我试图将一个字符串分开以保持在70个字符的限制之内...但是,当我这样做时,我的循环只是在它获得前70个字符时停止并且它不会尝试执行第2集。我走这条路线并且不使用str_split的原因是保留整个单词,所以我不会发出半个字的消息。如果第二次分割少于70个字符,请仍然发送出去...非常感谢任何形式的帮助。

$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;
    }
 }

2 个答案:

答案 0 :(得分:2)

<?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;
}

答案 1 :(得分:0)

$ msg包含什么?如果第一条消息包含49个或更少的字符,而第二条消息包含另外50个字符,则它不会发送第二条消息,是不是该点?

你可以在这里和那里放置一些var_dump来调试它。

相关问题