Validating phone numbers with PHP

For a new application, I am developing right now, I needed to validate international phone numbers. As you can imagine this is an interesting task for a developer, especially for international numbers. As every good developer does, I did some Google research to see if any developer has faced this problem before and if I could reuse some of his code or ideas. Indeed I found Making It Valid: Telephone Numbers by Ben Ramsey. This is a very nice approach for US phone numbers, as Ben not only validates the phone number against a regular expression as I thought of, but he extracts the different parts of the phone number out of a bunch of possible combinations. This is very usable (read: user friendly), because you are able to extract the neccessary parts of the phone number out of any syntax format you can think of and transform it into the right syntax that is required by your API or database.

I quickly “extended” Bens code to work with international phone numbers. Note that I allow up to five digits for the international dial code, because, although most countries have two or three digits, there are some satellite systems like Iridium, that use up to five digits.
Because, unlike Ben, I can not rely on set values for the length of each part of the number, I needed to make at least one space or dash between the different parts of the number mandatory.

This is my code, I hope you find it useful. If you manage to find any combination, that does not work (read: I forgot to think of), please send me a short note so that I can fix my code. Thanks.

  1. <?php
  2. function validatephonenumber($phonenumber) {
  3. $pattern = '/^(0+|\+)([1-9][0-9]{0,4})[\-|\s][\(]?([1-9][0-9]*)[\)]?[\-|\s]([1-9][0-9]*)$/';
  4. if(preg_match($pattern, $phonenumber, $matches)) {
  5. $phonenumber = $matches[0];
  6. $areacode = $matches[2];
  7. $exchange = $matches[3];
  8. $number = $matches[4];
  9. return '+'.$areacode.'-'.$exchange.'-'.$number;
  10. } // end if
  11. return FALSE;
  12. } // end function
  13. ?>

Shameless plug: If this post was useful to you, please consider buying yourself something from one of my Amazon stores: US store, UK store, FR store, DE store, CA store. If you're not into Amazon, why not donate something to GNOME, Mozilla or Wikipedia? Thank you!

Comments are closed.