Convert a mobile number into international format

You’ll have seen some of the plugins we’ve developed recently, noteably, shopify sms and magento sms.

Prior to these plugins the applications we’ve developed rely on the sender of the text message to input the mobile phone number, just as you do when you’re sending a text message from your mobile phone. You, as the sender, type in the recipients number.

This is generally foolproof because the sender has an inherent understanding of the number format required to send the text message.

With an eCommerce plugin we have another party to consider. The purchaser or “receiver” of the text message is the one who inputs their mobile number.

And they do so without any knowledge of the format the store owner needs to actually send the text message.

e.g. ask someone to fill in a form with their UK mobile number and you’ll get things like:

07741234567

07741 234567

07741 234 567

447741234567

447741 234567

+447741234567

44(0)7741234567

and so on, I think you get the picture.

Couple this with the international reach of most eCommerce applications and you’ve got people from all over the world inputting mobile numbers in all sorts of formats, and both the purchaser and their store owners expecting to receive text messages.

The answer is relatively simple, we need to convert any mobile number into a valid international format. That way we’ll have consistency in the data and our SMS API can route the messages to the appropriate country.

Here’s how we currently do it:

To do this you’ll need a table of international dialling codes. We use one hacked together from Wikipedia. Here’s the PHP code.

  1. Strip out any leading zeros.
  2. Remove any numbers within parentheses
  3. Strip any spaces or non numeric characters.
  4. Take the country of residence of the purchaser. If the purchaser didn’t input a country then use the store default, and look this up on the table of dialling codes.
  5. If the mobile number starts with the dialling code then great, you’re good to go.
  6. If not then add the dialling code to the start of the number, and then your good to go.

We are aware that this could be improved.

For instance, if the number starts with a ‘+’ then we could take it that the user has already supplied the country code.

We could also do this if the number starts with ’00′. That is for the UK though, other countries have other codes to dial an international number.

We will be looking at improving the process as we go on.