【问题标题】:PHP explode then double loopPHP爆炸然后双循环
【发布时间】:2015-05-12 08:42:40
【问题描述】:

我正在尝试拆分一个字符串以保持在 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;
    }
 }

【问题讨论】:

  • 能否请您连同字符串一起更新您的问题
  • 如果没有 $message,我们将无能为力,对不起。
  • 为什么你说的是 70 个字符并与 $msg&lt;50 比较???
  • 如我所见,如果 $message 少于 50 个字符,它将永远不会被发送
  • 添加了 $message.. 如果第二条消息有 30 个字符...仍然发送出去.. 只是不要发送超过 70 个字符的消息...

标签: php foreach explode


【解决方案1】:
<?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;
}

【讨论】:

  • 这行得通,但它不会发送剩余的消息……它只会发出第一个音调。
  • 你没有在你的规范中指定它:) 更新你的问题,我会更新我的回复
  • 这有点问题,我收到每个响应的 4 条消息...然后是最后一个响应的 12 条消息...
  • @thevoipman 我已经完全改变了我的方法并且我测试了它:)
【解决方案2】:

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

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

【讨论】:

  • 您的回复在哪里?请将其设置为评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
相关资源
最近更新 更多