PHP explode 然后双循环

标签 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;
    }
 }

最佳答案

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

关于PHP explode 然后双循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185839/

相关文章:

部分数组的java for-each循环

php - 使用 PHP foreach 构建样式表

arrays - hive中的数组操作(数组相加)

php - Wordpress-使用insert_post时出现db_insert_error

javascript - 通过javascript填充html表格

loops - 将一个变量的值替换为其他变量的值 Stata 13

javascript 数组到 mySQL

PHP - 删除部分字符串?

php - 图片上传在 Linkedin V2 API 中不起作用

php - SELECT FROM 子查询性能