Split SMS gateway response in PHP

I'm wondering what other approaches you would take for simple line splitting in PHP. I am getting a response from an SMS gateway where two of the interesting values ​​are a code and a text message from the users.

The code could be something like this: Freetrip

(lowercase, uppercase, mixed)

The custom message should at best be like for example: Freetrip 12345

($ code "space" XXXXX).

Each X must be a digit from 1 to 5. Any other value / character must return an error. So the regex will be simplified as: chars = 5, where each digit is> = 1 and <= 5.

What I need to keep at the end will be 5 digits long.

My simplest approach would be to capitalize the entire message line and subtract the lowercase code (plus space) from the message line as well. That would leave me with 5 digits, which I would then split into 5 unique variables to store in the DB.

Now, the tricky part is that the best scenario described above can be difficult to achieve. Typing SMS messages is difficult and typing errors occur easily. The following errors are possible:

  • Too few or too many numbers.
  • Non-digital characters.
  • More characters after the XXXXX combination.
  • Perhaps some other cases.

Any of these should return a separate error message that I can return to the sender.

0


a source to share


2 answers


if (!preg_match('/^freetrip\s+([1-5]{5})$/i', $sms, $matches)) exit("error");
print_r($matches);

      

I've had some experience with SMS platforms and AFAIK, one error is enough. We tried to find similar characters such as small L and big I, etc., or zero and O-letter. For example, in your case, you can write something like this:

preg_match('/^freetr[il1|]p\s+([1-5]{5})$/i', $sms, $matches);

      

you can do the same anywhere in the post template (if you like).



I did something like this (not sure - it was 5 years ago):

if (!preg_match('/^(\w+)\s+(.*)/i', $sms, $matches)) exit('bad message format');
$value = $matches[2];

// some letters look like digits
$value = str_replace(array('o', 'O'), 0);
$value = str_replace(array('i', 'I', 'l'), 1);
if (!preg_match('/^[12345]{5}/')) exit("invalid code");
// do something here... message is OK.

      

Of course, in this case, you can check "freetrip" or not, the value is [1-5] {5} or not, etc., and answer your error just like your imagination :). Good luck.

EDIT: the latter is being updated and should match your case. This is better because it will be very easy to create another service on it if you need to.

+1


a source


You can do something like this:



$code = 'Freetrip';
if (strlen($input) <= strlen($code)) {
    // too short
} elseif (!preg_match('/^'.preg_quote($code, '/').'(.*)/i', $input, $match)) {
    // wrong code
} else {
    $x = (int)trim($match[0]);
    if ($x < 11111) {
        // too small
    } elseif ($x > 55555) {
        // too large
    } else {
        // valid
    }
}

      

0


a source







All Articles