Php формат номера телефона

Php формат номера телефона

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Java приведение типов объектов

Источник

Форматирование телефонных номеров

Несколько PHP-функций для форматирования телефонных номеров.

Формат +7 (xxx) xxx-xx-xx

Формат +7 (xxx) xxx-xx-xx очень распространён, но правильнее писать номера без скобок. В нормах русского языка скобки используются для поясняющей и дополняющей информации, а так как без кода оператора или города дозвониться до абонента не получится, то это уже не дополнительная информация.

function phone_format($phone) < $phone = trim($phone); $res = preg_replace( array( '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', ), array( '+7 ($2) $3-$4-$5', '+7 ($2) $3-$4-$5', '+7 ($2) $3-$4-$5', '+7 ($2) $3-$4-$5', '+7 ($2) $3-$4', '+7 ($2) $3-$4', ), $phone ); return $res; >

Тестирование и результаты

Мобильные и городские:

echo phone_format('+7 (495) 1234567'); echo phone_format('+8 (495) 123 45 67'); echo phone_format('+7(495)123-45-67'); echo phone_format('+7(495)1234567'); echo phone_format('+7 495 123-45-67'); echo phone_format('+8 495 123 45 67'); echo phone_format('+7 495 1234567'); echo phone_format('+7-495-123-45-67'); echo phone_format('84951234567');
+7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67 +7 (495) 123-45-67

Региональные:

echo phone_format('7 4734 12-34-56'); echo phone_format('7 4735 123-456');
+7 (4734) 12-34-56 +7 (4735) 123-456

С текстом:

echo phone_format('+7-495-123-45-67 Иван'); echo phone_format('+84951234567 доп. 123'); echo phone_format('+74951234567, +79031234567'); echo phone_format('тел. +84951234567');
+7 (495) 123-45-67 Иван +7 (495) 123-45-67 доп. 123 +7 (495) 123-45-67, +7 (903) 123-45-67 тел. +7 (495) 123-45-67

Номера с ошибками:

echo phone_format('495 1234567'); echo phone_format('8(8001234567'); echo phone_format('8800;1234567');
495 1234567 8(8001234567 8800;1234567

Формат +7 xxx xxx-xx-xx

function phone_format($phone) < $phone = trim($phone); $res = preg_replace( array( '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', ), array( '+7 $2 $3-$4-$5', '+7 $2 $3-$4-$5', '+7 $2 $3-$4-$5', '+7 $2 $3-$4-$5', '+7 $2 $3-$4', '+7 $2 $3-$4', ), $phone ); return $res; >

Результат:

/* Мобильные и городские */ +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 +7 495 123-45-67 /* Региональные */ +7 4734 12-34-56 +7 4735 123-456 /* С текстом */ +7 495 123-45-67 Иван +7 495 123-45-67 доп. 123 +7 495 123-45-67, +7 903 123-45-67 тел. +7 495 123-45-67 /* Номера с ошибками */ 495 1234567 8(8001234567 8800;1234567

Формат +7-xxx-xxx-xx-xx

function phone_format($phone) < $phone = trim($phone); $res = preg_replace( array( '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', ), array( '+7-$2-$3-$4-$5', '+7-$2-$3-$4-$5', '+7-$2-$3-$4-$5', '+7-$2-$3-$4-$5', '+7-$2-$3-$4', '+7-$2-$3-$4', ), $phone ); return $res; >

Результат:

/* Мобильные и городские */ +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 +7-495-123-45-67 /* Региональные */ +7-4734-12-34-56 +7-4735-123-456 /* С текстом */ +7-495-123-45-67 Иван +7-495-123-45-67 доп. 123 +7-495-123-45-67, +7 903 123-45-67 тел. +7-495-123-45-67 /* Номера с ошибками */ 495 1234567 8(8001234567 8800;1234567

Формат +7xxxxxxxxxx

function phone_format($phone) < $phone = trim($phone); $res = preg_replace( array( '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?\([-|\s]?(\d)[-|\s]?\)[-|\s]?(\d)[-|\s]?(\d)/', '/[\+]?([7|8])[-|\s]?(\d)[-|\s]?(\d)[-|\s]?(\d)/', ), array( '+7$2$3$4$5', '+7$2$3$4$5', '+7$2$3$4$5', '+7$2$3$4$5', '+7$2$3$4', '+7$2$3$4', ), $phone ); return $res; >

Результат:

/* Мобильные и городские */ +74951234567 +74951234567 +74951234567 +74951234567 +74951234567 +74951234567 +74951234567 +74951234567 +74951234567 /* Региональные */ +74734123456 +74735123456 /* С текстом */ +74951234567 Иван +74951234567 доп. 123 +74951234567, +7 903 123-45-67 тел. +74951234567

Источник

Читайте также:  Javascript xmlhttprequest response json

Сниппет для форматирования телефонных номеров

Задача. Есть большой список телефонных номеров, которые нужно переформатировать под единый формат (или форматы). Номера есть нескольких типов 7, 10 и 11 значные. Для каждого из этих типов необходимо вывести номер телефона в своем формате.

В php есть такие функции как money_format и number_format, но нет такой функции как phone_format, этот пробел я и решил восполнить написав такую функцию для форматирования телефонных номеров.

/** * Форматирование телефонного номера * по шаблону и маске для замены * * @param string $phone * @param string|array $format * @param string $mask * @return bool|string */ function phone_format($phone, $format, $mask = '#') < $phone = preg_replace('/[^0-9]/', '', $phone); if (is_array($format)) < if (array_key_exists(strlen($phone), $format)) < $format = $format[strlen($phone)]; >else < return false; >> $pattern = '/' . str_repeat('(2)?', substr_count($format, $mask)) . '(.*)/'; $format = preg_replace_callback( str_replace('#', $mask, '/([#])/'), function () use (&$counter) < return '$'; >, $format ); return ($phone) ? trim(preg_replace($pattern, $format, $phone, 1)) : false; > 

Использование

Передаем в качестве параметров не отформатированный номер телефона, шаблон и маску для замены. В качестве шаблона также можно передать массив ключи которого это количество цифр в телефоне, а значение шаблоны замены

$phones = array( '926 111-2233', '9261112233', '8 (926) 111 22 33', '8 926 111-22-33', '559-8833', '5598833', '', 'qweqwe' ); $formats = array( '7' => '###-##-##', '10' => '+7 (###) ### ####', '11' => '# (###) ### ####' ); foreach ($phones AS $phone)

Результат выполнения радует глаз:

+7 (926) 111 2233 +7 (926) 111 2233 8 (926) 111 2233 8 (926) 111 2233 559-88-33 559-88-33 

Данный сниппет не ставит перед собой цель определить город, регион или какой-либо другой параметр. Кроме того возникнут проблемы при использовании шаблонов для номеров “8 (123) 111-22-33” и “+7 (123) 111-22-33”. Возможно потом придумаю как поступать с такими номерами.

Читайте также:  Time server using java

Источник

Format Phone Numbers in PHP

Format Phone Numbers in PHP

  1. Use the preg_match() Function to Format Phone Numbers in PHP
  2. Use the sprintf() Function to Format Phone Numbers in PHP

In this article, we will talk about different methods to format phone numbers using PHP. We will format the phone number from +13335092344 to 333-509-2344 .

Use the preg_match() Function to Format Phone Numbers in PHP

We can use the built-in function preg_match() to format phone numbers. This function searches a specified pattern from a string. The correct syntax to use this function is as follows.

preg_match($pattern, $inputString, $matches, $flag, $offset); 

This function returns a boolean variable. It returns true if the given pattern exists. After extracting the numbers, we will print them in the required format.

The program below shows the way by which we can use PHP preg_match() function to format phone numbers.

php $number = '+12333509234'; echo("The original number is $number.\n"); if( preg_match( '/^\+\d(\d)(\d)(\d)$/', $number, $matches ) )   $result = $matches[1] . '-' .$matches[2] . '-' . $matches[3]; > echo("The formatted number is $result."); ?> 

We have used /^\+\d(\d)(\d)(\d)$/ pattern to extract numbers from the string. The explanation of this pattern is as follows.

  • ^ is the symbol to match the start of the string.
  • \+ matches the + in the string. + is a special character in PHP to match one or more times of the preceding pattern. Therefore, we need to add \ before + to escape this special character.
  • \d is used to match the single digit number from 0-9. \d means that it will match three consecutive numbers.
The original number is +12333509234. The formatted number is 233-350-9234. 

Use the sprintf() Function to Format Phone Numbers in PHP

We can also use the sprintf() function to format phone numbers in PHP. This function gives several formatting patterns to format strings. We will extract the numbers using substr() function in several strings. After that, we will combine these strings in the required format using the sprintf() function. The correct syntax to use this function is as follows.

sprintf($formatString, $string1, $string2, . , $stringN) 

The function returns the formatted string. We will use the format %s-%s-%s to combine the numeric strings. The program that combines two strings is as follows.

php $number = '+12333509234'; echo("The original number is $number.\n"); $result = sprintf("%s-%s-%s",  substr($number, 2, 3),  substr($number, 5, 3),  substr($number, 8)); echo("The formatted number is $result."); ?> 
The original number is +12333509234. The formatted number is 233-350-9234. 

Related Article — PHP Regex

Источник

Оцените статью