phone.ch.inc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * @file
  4. * CCK Field for Switzerland phone numbers.
  5. */
  6. define('PHONE_CH_REGEX', "%(\+41|0|0041)([2-9]\d{8})$%");
  7. function phone_ch_metadata() {
  8. // These strings are translated using t() on output.
  9. return array(
  10. 'error' => '"%value" is not a valid Swiss phone number<br>Swiss phone numbers should only contain numbers and spaces and be like 099 999 99 99',
  11. );
  12. }
  13. /**
  14. * Verification for private/standr switzerland Phone Numbers (E.164/2002).
  15. * According to http://en.wikipedia.org/wiki/Telephone_numbers_in_Switzerland#After_2002
  16. * (Released 2002)
  17. *
  18. * @param string $phonenumber
  19. * @return boolean Returns boolean FALSE if the phone number is not valid.
  20. */
  21. function valid_ch_phone_number($phonenumber) {
  22. $phonenumber = str_replace(array(' ','-','.','/','(',')'), '', $phonenumber);
  23. $match =array();
  24. $result = (bool) preg_match(PHONE_CH_REGEX, $phonenumber, $match);
  25. return $result;
  26. }
  27. /**
  28. * Formatting for Switzerland Phone Numbers.
  29. *
  30. * @param string $phonenumber
  31. * @return string Returns a string containting the phone number with some formatting.
  32. */
  33. function format_ch_phone_number($phonenumber, $field = FALSE) {
  34. $phone = str_replace(array(' ','-','.','/','(',')'), '', $phonenumber);
  35. $matches =array();
  36. if (preg_match(PHONE_CH_REGEX, $phone, $matches) != 1) {
  37. return $phonenumber; // not a switzerland phone number
  38. }
  39. $value =($field && $field['phone_country_code'] ? '+41 (0)' : '0') .
  40. substr($matches[2],0,2).
  41. ' '.substr($matches[2],2,3).
  42. ' '.substr($matches[2],5,2).
  43. ' '.substr($matches[2],7);
  44. return $value;
  45. }