我的客户正在寻找一种方法来向我编写的 Twilio PHP 脚本发送文本消息,然后将其转播给现场人员。这是简单的部分,只需检查传入号码是否已授权,从 MySQL 中提取人员详细信息,然后分发。
这是棘手的部分 - 使用此功能的人可能会啰嗦,而且他们的手机允许他们输入超过 160 个字符。假设 Twilio 可以接收 >160 个字符(我知道它不能发送 >160 个),我需要将这条长消息(字符串)分解成 160 个字符以内的 block 。
这是我想出的脚本,它工作得很好,但我希望它以一个完整的单词结束,而不是简单地在拆分后的下一个字符上结束。有趣的故事,当你忘记输入分割字符串的长度时,你会收到 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 的实时脚本。我需要能够遍历这些 block ,以便在拆分后将每个 block 作为自己的 SMS 发送出去,就像上面那样......只是以一个完整的词结尾。 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 已更新
关于php - 用 PHP 分解长字符串以发送短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5017056/