我的客户正在寻找一种方法来向我编写的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...
}
}
?>
非常感谢
CORRECTION 对不起,我的主要疏忽 - 我发布了开发脚本以使用字符串而不是在“事件”之后发送实际短信的实时脚本。我需要能够迭代这些块,在分割之后将它们作为自己的短信发送出去,就像上面所做的那样......只是以一个完整的单词结尾。 SMS将在foreach循环中发送。
答案 0 :(得分:8)
当你可以使用时,我不明白为什么所有过于复杂的答案:
$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 已更新
答案 1 :(得分:1)
您可以先使用空格作为分隔符explode()字符串。获得数组后,开始循环遍历并逐个向字符串添加单词。在将字添加到字符串之前,检查总字符串长度是否超过160。如果是这样,请启动一个新字符串。您可以通过存储字符串数组来完成此操作。
<?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 = explode(' ', $string); // explode by space
$msgs = array(); // array of finished messages
$i = 0; // position within messages array
foreach($arr as $word)
{
if (strlen($msgs[$i] . $word) <= 155) // this may be 160, im not sure
{
$msgs[$i] .= $word;
}
else
{
$i++;
$msgs[$i] = $word;
}
}
?>
答案 2 :(得分:1)
尝试wordwrap:http://www.php.net/manual/en/function.wordwrap.php
<?php
$words = "this is a long sentence that needs splitting";
foreach(explode("\n", wordwrap($words, 10, "\n")) as $s) {
echo $s . "\n";
}
答案 3 :(得分:0)
这个怎么样(注意:未经测试,非我头脑,但你明白了):
$string = '<your long message>';
$parts = array();
while (strlen($string) > 155) {
$part = substr($string, 0, 155);
$lastSpace = strrpos($part, ' ');
$parts[] = substr($string, 0, $lastSpace);
$string = substr($string, $lastSpace);
}
$parts[] = $string;
var_dump($parts);