使用PHP分解长字符串以用于传出SMS

我的客户正在寻找一种方法来向我编写的Twilio PHP脚本发送文本消息,然后将其重新广播给该领域的人员.这是一个简单的部分,只需检查传入的号码是否被授权,从MysqL提取人员详细信息并分发.

这是一个棘手的部分 – 使用它的人可能会啰嗦,他们的手机允许他们输入超过160个字符.假设Twilio可以接收> 160个字符(我知道它不能发送> 160),我需要将这个长消息(字符串)分成多达160个字符的块.

这是我想出来的脚本,它运行得很好,但我希望它以一个完整的单词结束,而不是简单地分割后的下一个字符.有趣的侧面故事,当你忘记输入分割字符串的长度时,你会收到171个左右的一个字符短信! :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...
}

}
?>

非常感谢

更正
对不起,我的主要疏忽 – 我发布了开发脚本以使用字符串而不是在“事件”之后发送实际短信的实时脚本.我需要能够迭代这些块,在分割之后将它们作为自己的短信发送出去,就像上面所做的那样……只是以一个完整的单词结束. SMS将在foreach循环中发送.

当你可以使用时,我不明白为什么所有过于复杂的答案:
$chunks = explode("||||",wordwrap($message,155,"||||",false));
$total = count($chunks);

foreach($chunks as $page => $chunk)
{
    $message = sprintf("(%d/%d) %s",$page+1,$total,$chunk);
}

这将产生类似于:

(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.

在线示例:http://codepad.org/DTOpbPIJ已更新

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...