- Phone number regex PHP
- The basic international phone number validation
- Extra information about validating phone number
- Create an internal tool with UI Bakery
- Простейший способ валидации телефонных номеров на сайтах
- Simple Way to Validate Phone Numbers in PHP
- How to validate phone number in PHP
- 1. Create the function
- 2. Create the statement
- 3. Call the function
- Format variation of phone numbers
- Cell phones
- Special characters
- International numbers
- Validation phone number with an API
- Wrapping up
- Проверка данных регулярными выражениями
- Проверка чисел
- Проверка даты по формату
- Проверка номера телефона
- Проверка E-mail
- Логин
- Проверка md5-хэша
- Цвета
- IP адреса
- Комментарии
- Другие публикации
Phone number regex PHP
The regular expressions below can be used to validate if a string is a valid phone number format and to extract a phone number from a string. Please note that this validation can not tell if a phone number actually exists.
The basic international phone number validation
A simple regex to validate string against a valid international phone number format without delimiters and with an optional plus sign:
Enter a text in the input above to see the result
The more complex phone number validation
This regular expression will match phone numbers entered with delimiters (spaces, dots, brackets, etc.)
Enter a text in the input above to see the result
Enter a text in the input above to see the result
Extra information about validating phone number
While validation of phone numbers using regex can give a possibility to check the format of the phone number, it does not guarantee that the number exists.
There might be also an option to leave a phone number field without any validation since some users might have:
- More complex phone numbers with extensions
- The different phone numbers for calling them on a different time of day
Create an internal tool with UI Bakery
Discover UI Bakery – an intuitive visual internal tools builder.
Простейший способ валидации телефонных номеров на сайтах
Ещё одна раздражающая проблема многих сайтов — это когда сайт заставляет вводить тебя телефонный номер в понятном ЕМУ формате. Часто разработчики таких сайтов впридачу не удосуживаются сообщить пользователю, в каком формате сайт хочет видеть номер. Совсем клиника — когда ты видишь голое поле ввода номера, вводишь номер, жмёшь «Отправить» и получаешь сообщение типа «Телефон введён неправильно». Блин, а как правильно-то? И начинаешь перебирать разные форматы.
Сегодня рассмотрим простой способ валидации (проверки правильности ввода) телефонных номеров при условии того, что все посетители сайта — из России (или Казахстана). Российские номера телефонов начинаются с +7 и имеют далее 10 цифр. При этом, все люди привыкли вводить телефонные номера по-разному. Кто-то пишет кто-то кто-то ставит скобки и тире: кто-то пишет через восьмёрку: 89219710296, кто-то пишет просто 10 цифр: 921 971 02 96, ну и так далее. В нашем способе проверки все эти примеры будут считаться валидными, а на выходе мы будем иметь телефон в едином формате +7xxxxxxxxxx для удобного хранения номера в базе данных.
function validate_russian_phone_number($tel) < $tel = trim((string)$tel); if (!$tel) return false; $tel = preg_replace('#[^0-9+]+#uis', '', $tel); if (!preg_match('#^(?:\\+?7|8|)(.*?)$#uis', $tel, $m)) return false; $tel = '+7' . preg_replace('#[^0-9]+#uis', '', $m[1]); if (!preg_match('#^\\+75$#uis', $tel, $m)) return false; return $tel; >
Функция принимает на входе строку с телефонным номером в произвольном формате, а возвращает либо телефонный номер в формате +7xxxxxxxxxx , либо false в случае, если номер не прошёл проверку (и об этом следует сообщить пользователю).
Simple Way to Validate Phone Numbers in PHP
In today’s world, assuring real sign-ups is critical for your business. Without genuine registrations, your marketing campaign will fail miserably. Email address validation is a popular way of verifying real sign-ups. But phone number validation works as an extra layer of security. It helps you to prevent fraudulent activities effectively. In this post, you will find a simple way of validating phone numbers using PHP code. We also have other similar guides, for geolocating IP addresses using PHP and validating email addresses using PHP.
Don't reinvent the wheel.
Abstract's APIs are production-ready now.
Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.
How to validate phone number in PHP
The easiest way to create a PHP validate phone number function is using inbuilt PHP filters.
However, developers around the world are preferring to use regular expressions. PHP provides powerful functions for parsing regular expressions. So, you can validate phone number with different types of formats effectively.
To validate phone number using regular expression, you have to follow these steps:
1. Create the function
Create a PHP validate phone number function, called validating(), with a parameter of $phone.
2. Create the statement
Then you have to create an if/else statement for determining whether the given phone number is valid or not. Let’s say that the genuine phone number is 10 digits long, ranging from 0 to 9. To perform the validation, you have to utilize this regular expression: /^4+$/. Also, you have to use the reg_match() function.
if(preg_match('/^6+$/', $phone)) < echo "Valid Phone Number"; >else
If the given telephone number matches the specified regular expression, it will print “Valid Phone Number.” Otherwise, it will print “Invalid Phone Number” as the error message.
3. Call the function
Now, let’s try verifying different phone numbers by calling our validating() function for number validation in PHP:
validating("1016660180"); //10 digits valid phone number validating("101666018000"); //12 digits invalid phone number validating("101$666*01"); //10 letters phone number with invalid characters validating("101$666*0180"); //10 digits phone numbers with invalid characters
4. You will see this output:
Valid Phone Number Invalid Phone Number Invalid Phone Number Invalid Phone Number
Overall, the following code will look like this:
function validating($phone)< if(preg_match('/^5+$/', $phone)) < echo " Valid Phone Number"; >else < echo " Invalid Phone Number"; >> validating("1016660180"); //10 digits valid phone number validating("101666018000"); //12 digits invalid phone number validating("101$666*01"); //10 letters phone number with invalid characters validating("101$666*0180"); //10 digits phone numbers with invalid characters
That’s it! You have learned the way of validating phone numbers in PHP using regular expressions. The same rules apply to mobile number validation.
Format variation of phone numbers
Phone numbers have different formats. So, verifying them could have been really challenging. Fortunately, using a PHP function has made the process very simple.
As said earlier, the in-built PHP filter can make it easier for you to validate phone number. Here, you will use it to validate numbers with different formats.
Cell phones
1. First, you have to create a function, called validating().
2. Create a variable, called valid_number. It will have the filter_var() function with a FILTER_SANITIZE_NUMBER_INT constant.
$valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
3. Now, you can print the valid_number variable.
4. Finally, let’s call the validating() PHP function with for mobile number validation.
You will see this output: 101-666-0260
Overall, the code will look like this:
function validating($phone) < $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number.; >validating("101-666-0260");
That’s how you validate a cell phone number with the in-built PHP filter.
Special characters
A phone number can have certain characters, like + and -. But what will happen if the user enters the number incorrectly with special characters, like $ and *? You need to find a way to filter them out.
By using filter_var() function, you can strip them off from the given phone number.
Let’s try validate a phone number that contains $ and *, like this: 101$777*0280
function validating($phone) < $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number.; >validating("101$777*0280");
You will see an output with $ and * being removed from the given phone number: 1017770280
International numbers
International phone numbers start with + with some also needing the area code. So, you need to figure out a way to prevent it from being filtered out. Fortunately, filter_var() function supports the + sign. So, you will never have to worry about it being stripped off.
Let’s try performing something for international users, for example an Indian phone number validation. The number looks like this: +91-202-5555-0234
As you can see, the country code of India is +91. How will filter_var() function react if an Indian phone number is entered? Will it filter out the + sign?
Let’s use this code to figure out what happens:
function validating($phone) < $valid_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT); echo $valid_number.; >validating("+91-202-5555-0234");
You will see an output like this: +91-202-5555-0234
As you can see, the filter_var() function supports the + sign. So, it’s not being filtered out.
Validation phone number with an API
By using APIs, you can validate phone numbers effortlessly. They come with all the necessary functions for verification. You just need to enter the number. The API will handle the rest. You don’t have to write any code from scratch. So, you can validate the phone numbers effortlessly.
You can try using Abstract’s phone number validation and verification API. It is reliable, blazing-fast, and easy to maintain. It can help you to validate phone numbers effortlessly.
Let’s use Abstract’s Phone Number Validation and Verification API to validate this phone number: 14154582468.
https://phonevalidation.abstractapi.com/v1/ ? api_key = YOUR_UNIQUE_API_KEY & phone = 14154582468
If the phone number request is successful, you will see this output:
The given phone number is valid, as the "valid" field is set to “true.” Also, it provides you with a variety of geolocation data, including country name and registered location of the phone number. You can utilize this information to enhance your marketing strategy.
As you can see, you don’t have to write any code from scratch. There is no need to utilize regular expressions or PHP in-built functions. You just need to get the API key and enter the phone number that you want to verify. Abstract’s Phone Number Validation and Verification API will handle the rest.
Wrapping up
That’s how you validate phone numbers using PHP procedural programming. You can use regular expressions or PHP in-built functions. However, the easiest way is to utilize a verification API. It will help you to validate the phone numbers effortlessly.
Validate phone numbers using Abstract's API
Проверка данных регулярными выражениями
Сборник регулярных выражений с примерами на PHP для проверки данных из полей форм.
Проверка чисел
$text = '1'; if (preg_match("/^\d+$/", $text)) < echo 'yes'; >else
Числа с плавающей точкой (разделитель точка):
$text = '-1.0'; if (preg_match("/^\-?\d+(\.\d)?$/", $text)) < echo 'yes'; >else
Проверка даты по формату
$text = '02.12.2018'; if (preg_match("/^(04|[12]2|3[01])[\.](08|1[012])[\.](19|20)\d\d$/", $text)) < echo 'yes'; >else
$text = '2018-04-02'; if (preg_match("/^2-(07|1[012])-(02|14|22|3[01])$/", $text)) < echo 'yes'; >else
Проверка номера телефона
Ориентировано на российские мобильные + городские с кодом из 3 цифр.
$text = '+7(495)000-00-00'; if (preg_match("/^((8|\+7)[\- ]?)?(\(?\d\)?[\- ]?)?[\d\- ]$/", $text)) < echo 'yes'; >else
Проверка E-mail
$text = 'mail@snipp.ru'; if (preg_match("/^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]$/i", $text)) < echo 'yes'; >else
Логин
Латинские буквы, цифры, - и _ .
$text = 'admin-1'; if (preg_match("/^[a-z0-9_-]$/i", $text)) < echo 'yes'; >else
Проверка md5-хэша
$text = 'ca040cb5d6c2ba8909417ef6b8810e2e'; if (preg_match("/^[a-f0-9]$/", $text)) < echo 'yes'; >else
Цвета
Шестнадцатеричные коды цветов #FFF и #FFFFFF .
$text = '#fff'; if (preg_match("/^#(?:(?:[a-fd]))$/i", $text)) < echo 'yes'; >else
IP адреса
$text = '192.168.0.1'; if (preg_match("/^((251|22\d|[01]?\d\d?)\.)(254|24\d|[01]?\d\d?)$/", $text)) < echo 'yes'; >else
$text = '2001:DB8:3C4D:7777:260:3EFF:FE15:9501'; if (preg_match("/((^|:)([0-9a-fA-F]))$/i", $text)) < echo 'yes'; >else
Комментарии
Другие публикации
Применение масок ввода у полей форм значительно упрощает их использование, уменьшает количество ошибок и приводит.
Несколько примеров, как сгенерировать случайные последовательности численных и буквенных строк заданной длины и.
Протокол FTP – предназначен для передачи файлов на удаленный хост. В PHP функции для работы с FTP как правило всегда доступны и не требуется установка дополнительного расширения.
В следующей таблице приведены имена констант (VK Codes), десятичные и шестнадцатеричные значения для кодов виртуальных.
В статье приведен пример формы и php-скрипта для безопасной загрузки файлов на сервер, возможные ошибки и рекомендации при работе с данной темой.