Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split up a message longer than 160 chars into multiple messages for sending SMS (PHP)

Tags:

php

I am working on a small project that sends SMS Messages. I already have the message classes written, and ready to send back in the correct format.

However, I am having a technical design issue. I'm sure it is easily solved, but I haven't come across this issue before so I am lost in the dark.

When I return a message longer than 160 chars, it obviously needs broken down into smaller messages and sent individually. My first thoughts are obviously to get the string length, then divide it by 160 chars, and round up to the greatest whole number (since you cannot send 2.5 messages,only 3) and then each sms needs to have 1/3, 2/3, 3/3 etc in the message as well showing the user which order to read them in. (trust me, they will need it)

My thoughts are obviously using some kind of loop to create a 'new ServiceMessage()' for each 160 char message. But I am unsure exactly how to do it, as well as unsure how to show the count of message (1/2, 2/3, etc).

Fairly simple, I am sure, but this is my first shot at it - so any help is greatly appreciated! Thank you!

like image 535
Alpinestar22 Avatar asked Dec 21 '25 06:12

Alpinestar22


1 Answers

$messages = str_split($message , 160);
foreach($messages as $message){
   // send $message
}

A more complicated version with the number of message itself can be like this, the code is untested:

if(strlen($message) > 160){
    /// lets use 152 characters and keep room for message number like (1/10), 
    /// we can have upto 99 parts of the message (99/99)

    $messages = str_split($message , 152); 
    $how_many = count($messages);
    foreach($messages as $index => $message){
        $msg_number = ($index + 1);
        $message = "(".$msg_number."/".$how_many.") ".$message;

        // send $message
    }
}
else{
    // send $message
}

The above might waste 2 characters per message but it keeps the calculation rather simple.

like image 103
Sabeen Malik Avatar answered Dec 22 '25 18:12

Sabeen Malik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!