You are here

function format_ca_phone_number in Phone 5

Same name and namespace in other branches
  1. 6 phone.ca.inc \format_ca_phone_number()
  2. 7 include/phone.ca.inc \format_ca_phone_number()

Convert a valid North American phone number into standard (444) 867-5309 x1234 format

Parameters

$phonenumber must be a valid ten-digit number (with optional extension):

File

./phone.ca.inc, line 38

Code

function format_ca_phone_number($phonenumber, $field) {

  // define regular expression
  $regex = "/\n    ^\\D*          # ignore non-digits\n    1?            # an optional 1\n    \\D*           # optional separator \n    ([2-9]\\d{2})  # capture area code       \n    \\D*           # optional separator\n    ([2-9]\\d{2})  # capture 3-digit prefix\n    \\D*           # optional separator\n    (\\d{4})       # capture 4-digit line number                       \n    \\D*           # optional separator\n    (\\d*)         # capture optional extension                       \n    \\D*\$          # ignore trailing non-digits\n  /x";

  // get digits of phone number
  preg_match($regex, $phonenumber, $matches);

  // construct ten-digit phone number
  $phonenumber = $matches[1] . '-' . $matches[2] . '-' . $matches[3];

  // Optional extension
  if ($matches[4] != '') {
    $phonenumber .= $matches[4];
  }
  if ($field['phone_country_code']) {
    if ($matches[1] != "1") {
      $phonenumber = "1" . " " . $phonenumber;
    }
  }
  return $phonenumber;
}