You are here

function format_nz_phone_number in Phone 6

Same name and namespace in other branches
  1. 7 include/phone.nz.inc \format_nz_phone_number()

Formatting for New Zealand Phone Numbers.

Parameters

string $phonenumber:

Return value

string Returns a string containing the phone number with some formatting.

File

./phone.nz.inc, line 128
CCK Field for New Zealand phone numbers.

Code

function format_nz_phone_number($phonenumber, $field) {
  $prefix = '';
  $extension = '';

  // strip old formatting chars
  $phonenumber = preg_replace('/[\\-() ]/', '', $phonenumber);

  /*
   * strip and save the +64 prefix if found
   */
  if (preg_match('/^\\+64/', $phonenumber, $match)) {
    $prefix = '+64';
    $phonenumber = str_replace('+64', '', $phonenumber);
  }
  else {
    $prefix = '0';

    /*
     * Remove a leading 0, if present
     */
    if (preg_match('/^0/', $phonenumber, $match)) {
      $phonenumber = substr($phonenumber, 1);
    }
  }

  /*
   * strip and save the extension (x9999) postfix if found
   */
  if (preg_match('/(x[0-9]+)$/', $phonenumber, $match)) {
    $extension = ' ' . $match[1];
    $phonenumber = preg_replace('/x[0-9]+$/', '', $phonenumber);
  }

  /*
   * geographic numbers
   * Eg. (04) 123 4578
   */
  if (preg_match('/^([34679])([0-9]{3})([0-9]{4})$/', $phonenumber, $match)) {
    return _format_nz_phone_number_prefix($prefix, $match[1]) . $match[2] . ' ' . $match[3] . $extension;
  }

  /*
   * 8 digit mobile numbers
   * Eg. 021 123 123
   */
  if (preg_match('/^(2[12679])([0-9]{3})([0-9]{3})$/', $phonenumber, $match)) {
    return _format_nz_phone_number_prefix($prefix, $match[1]) . $match[2] . ' ' . $match[3] . $extension;
  }

  /*
   * 9 digit mobile numbers
   * Eg. 021 123 4567
   */
  if (preg_match('/^(2[12679])([0-9]{3})([0-9]{4})$/', $phonenumber, $match)) {
    return _format_nz_phone_number_prefix($prefix, $match[1]) . $match[2] . ' ' . $match[3] . $extension;
  }

  /*
   * 10 digit mobile numbers
   * Eg. 021 1234 1234
   */
  if (preg_match('/^(2[12679])([0-9]{4})([0-9]{4})$/', $phonenumber, $match)) {
    return _format_nz_phone_number_prefix($prefix, $match[1]) . $match[2] . ' ' . $match[3] . $extension;
  }

  /**
   * 0800/0900 numbers (a bit random)
   */
  if (preg_match('/^(900|800)(\\d+)$/', $phonenumber, $match)) {

    // How we format depends on the length
    $formatted = null;
    switch (strlen($match[2])) {
      case 5:
        $formatted = preg_replace('/^(\\d{2})(\\d{3})$/', '$1$2', $match[2]);
        break;
      case 6:
        $formatted = preg_replace('/^(\\d{3})(\\d{3})$/', '$1$2', $match[2]);
        break;
      case 7:
        $formatted = preg_replace('/^(\\d{3})(\\d{4})$/', '$1 $2', $match[2]);
        break;
    }
    return _format_nz_phone_number_prefix($prefix, $match[1]) . $formatted;
  }

  // default (probably bad)
  return $prefix . $phonenumber . $extension;
}