вторник, 27 июня, 2017 - 15:27

Функция выводит телефон в читабельном виде.

С аргументом $clear = TRUE выводит телефон в чистом виде "+79998887766".

function format_telephone($telephone, $clear = FALSE) {
  // clear
  $telephone = preg_replace('/[^\d]+/', '', $telephone);

  $length = drupal_strlen($telephone);
  if ($length == 11 && $telephone{0} == 7) {
    $telephone = "+{$telephone}";
    $length += 1;
  }

  // format clear
  if ($clear) {
    return $telephone;
  }

  // format
  switch ($length) {
    case 7:
      $telephone = preg_replace('/(\d{3})(\d{2})(\d{2})/', '$1-$2-$3', $telephone);
      break;

    case 10:
      $telephone = preg_replace('/(\d{3})(\d{3})(\d{2})(\d{2})/', '+7 $1 $2-$3-$4', $telephone);
      break;

    case 11:
      $telephone = preg_replace('/8(\d{3})(\d{3})(\d{2})(\d{2})/', '+7 $1 $2-$3-$4', $telephone);
      break;

    case 12:
      $telephone = preg_replace('/\+7(\d{3})(\d{3})(\d{2})(\d{2})/', '+7 $1 $2-$3-$4', $telephone);
      break;
  }

  return $telephone;
}

Пример

$telephone = format_telephone('+7(999)888-7766'); // +7 999 888-77-66
$href = 'call:' . format_telephone('+7(999)888-7766', TRUE); // +79998887766

return format_string('<a href="@href">@text</a>, array(
    '@text' => $telephone,
    '@href' => $href
  ));