Format Phone Numbers Using PHP| 5 Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

If you’re working with phone numbers in your PHP code, it’s important to format them correctly. Properly formatted phone numbers are easier to read and help avoid errors when making calls or sending text messages. 

How to Format Phone Numbers in PHP

In this guide, we’ll cover everything you need to know about formatting phone numbers in PHP, including the different phone number formats, phone number validation, formatting phone numbers using PHP functions, handling exceptions, best practices, and more.

PHP Format Phone Numbers Code Example

<?php

require_once('vendor/autoload.php'); // Load the library

use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberType;
use libphonenumber\PhoneNumber;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberProto = $phoneUtil->parse('1234567890', 'US'); // Parse the phone number

$formattedNumber = $phoneUtil->format($numberProto, PhoneNumberFormat::NATIONAL); // Format the phone number

echo $formattedNumber; // (123) 456-7890

?>

Article Highlights

  • Different phone number formats exist, including national, international, and E.164.
  • Validating phone numbers is important before formatting them in PHP.
  • You can format phone numbers in PHP using: substr(), preg_match(), or the libphonenumber library.
  • Handling exceptions is important when formatting phone numbers in PHP.
  • Best practices include using consistent formatting, storing phone numbers as strings, and allowing for different formats.

Table of Contents

Format Phone Numbers in PHP

Types of Phone Number Formats

Different phone number formats exist, including national, international, and E.164

The national format is used for phone numbers within a specific country.

  • North America: (555) 555-5555
  • United Kingdom: 020 1234 5678
  • Australia: 02 1234 5678
  • Japan: 03-1234-5678

The international format is used for phone numbers intended to be dialed from outside the country. An international phone number includes a plus sign (+) followed by the country code, city code, and local phone number.

  • +1 212-555-1212 (USA)
  • +44 20 7123 4567 (UK)
  • +81 3-1234-5678 (Japan)
  • +86 10 1234 5678 (China)

E.164 is a standardized format that includes the country code, area code, and local number, with no spaces or other characters.

  • +1 212-555-1234 – This is a North American number in the E.164 format, with the country code “+1” followed by the area code “212” and the seven-digit phone number “555-1234”.
  • +44 20 7123 4567 – This is a British number in the E.164 format, with the country code “+44” followed by the area code “20” and the eight-digit phone number “7123 4567”.
  • +86 10 1234 5678 – This is a Chinese number in the E.164 format, with the country code “+86” followed by the area code “10” and the eight-digit phone number “1234 5678”.
  • +81 3 1234 5678 – This is a Japanese number in the E.164 format, with the country code “+81” followed by the area code “3” and the eight-digit phone number “1234 5678”.

Phone Number Validation

Before formatting a phone number in PHP, it’s important to validate it. One way to validate a phone number in PHP is to use regular expressions or third-party libraries like libphonenumber. You can also use PHP’s built-in preg_match() function to validate phone numbers.

Stay tuned at FuelingPHP for an article on validating phone numbers in PHP.

Format Phone Numbers in PHP using substr()

PHP substr() function returns part of a string based on the provided offset & length arguments. The following examples use the substr() function to segment a string representing a phone number. 

Format national phone numbers in PHP using substr()

<?php


function formatPhoneNumberWithSubstr($phoneNumber) {
   if (!is_numeric($phoneNumber)) {
     return false;
   }
    $phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
    if (strlen($phoneNumber) !== 10) {
     return false;
   }
    $areaCode = substr($phoneNumber, 0, 3);
   $prefix = substr($phoneNumber, 3, 3);
   $lineNumber = substr($phoneNumber, 6);
    return '(' . $areaCode . ') ' . $prefix . '-' . $lineNumber;
}


formatPhoneNumberWithSubstr('5555555555'); //(555) 555-5555


?>

This function takes a phone number as a parameter and returns it in the national format using substr(). 

First, it checks if the phone number is numeric and removes non-numeric characters. If the length of the phone number is not 10 digits, it returns false. Otherwise, it extracts the area code, prefix, and line number using substr() and formats the phone number accordingly.

The function uses a pre-defined delimiter and length of segments in a national phone number. However, these can be parameterized. 

Format international phone numbers in PHP using substr()

For international numbers, the function is somewhat similar.

<?php
function formatIntlPhoneNumberWithSubstr($phoneNumber) {


   if (!is_numeric($phoneNumber)) {
     return false;
   }
    if (strlen($phoneNumber) < 10) {
     return false;
   }
    $country_code = substr($phoneNumber, 0, 3); // get the country code (e.g. "+1")
   $area_code = substr($phoneNumber, 3, 2); // get the area code (e.g. "415")
   $prefix = substr($phoneNumber, 5, 4); // get the prefix (e.g. "555")
   $line_number = substr($phoneNumber, 9, 4); // get the line number (e.g. "2671")
    // format the phone number with parentheses and hyphens
   return $country_code . ' (' . $area_code . ') ' . $prefix . '-' . $line_number;
}

echo formatIntlPhoneNumberWithSubstr("+442071234567"); //+44 (20) 7123-4567
?>

Limitation | Format phone numbers in PHP using substr() 

While substr() can be a useful tool for extracting parts of a string, including international phone numbers, it also has some limitations when it comes to handling the various formats and rules associated with phone numbers from different countries and regions. 

Here are some limitations of using substr() for formatting international phone numbers.

  1. It assumes that the phone number has a fixed format and length, which may not be true.
  1. Some countries have specific rules around phone number length, and formatting substr() may be unable to handle.
  1. Phone number formats and rules can change as technology evolves and new standards are adopted. substr() may not be able to handle these changes.

Luckily, it is not the only PHP option to format phone numbers. Let’s explore other options.

Format Phone Numbers in PHP using preg_match()

The preg_match() is a PHP function that allows developers to search a string for a specified pattern. This function can extract specific characters from a phone number and format it in the desired way.

Format national phone numbers in PHP using preg_match()

<?php
function formatPhoneNumberWithPregMatch($phoneNumber) {


   $phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
    if (!preg_match('/^(\d{3})(\d{3})(\d{4})$/', $phoneNumber, $matches)) {
     return false;
   }
    return '(' . $matches[1] . ') ' . $matches[2] . '-' . $matches[3];
}


formatPhoneNumberWithPregMatch("5555555555"); //(555) 555-5555
?>

We use preg_match() to search for a phone number pattern in this example. The pattern we are searching for is (\d{3})-(\d{3})-(\d{4}), which matches a phone number in the format 123-456-7890. The parentheses indicate that we want to capture each group of digits as a separate match.

Once we have found a match, we can use the captured groups to format the phone number in the desired way. In this case, we format the phone number as (123) 456-7890.

Again, the output format can be customized to your needs and can be parameterised too. 

Format international phone numbers in PHP using preg_match()

Similarly, the only change for international numbers has to happen in the Regex pattern.

<?php
function formatIntlPhoneNumberWithPregMatch($phoneNumber) {


     // check if the number starts with a plus sign and has at least 10 digits
     if (preg_match('/^\+(?:[0-9] ?){6,14}[0-9]$/', $phoneNumber)) {
       // format the phone number with parentheses and hyphens
       $formatted_number = preg_replace('/\D/', '', $phoneNumber); // remove all non-numeric characters
       $formatted_number = '+' . substr($formatted_number, 0, 2) . ' (' . substr($formatted_number, 2, 2) . ') ' . substr($formatted_number, 4, 4) . '-' . substr($formatted_number, 8);


       return $formatted_number;
   } else {
       // if the number is not in the correct format, return an error message
       return 'Error: Invalid phone number format.';
   }


}


formatIntlPhoneNumberWithPregMatch("+442071234567");  //+44 (20) 7123-4567
?>

The regular expression ‘/^\+(?:[0-9] ?){6,14}[0-9]$/’ matches a string that starts with a plus sign, followed by 6 to 14 groups of digits with an optional space after each group, and ending with a digit.

Limitation | Format phone numbers in PHP using preg_match() 

While preg_match() can be a useful tool for validating and formatting certain types of strings, including international phone numbers, it does have some limitations when handling the various formats and rules associated with phone numbers from different countries and regions. 

Here are some limitations of using preg_match() for formatting international phone numbers.

  1. Phone numbers have different formats depending on the country and region. Writing a regular expression that can handle these different formats can be difficult.
  1. International phone numbers can range from 10 to 15 digits with varying phone number lengths and formatting rules. Creating a regular expression that can handle these different lengths and rules can be challenging.
  1. Phone number formats and rules can change as technology evolves and new standards are adopted. It can be difficult to keep up with these changes and ensure that your regular expressions are up to date.
  1. Regular expressions can sometimes match strings that are not valid phone numbers or fail to match valid phone numbers that do not fit the expected pattern.

Because of these limitations, using a specialized library or API designed to handle international phone numbers is often best rather than relying solely on regular expressions. These tools can provide robust validation and formatting capabilities and be more easily updated to reflect phone number rules and standard changes.

Format Phone Numbers in PHP using the libphonenumber library

One popular tool for formatting phone numbers in PHP is the libphonenumber library. This library provides a comprehensive set of tools for working with phone numbers, including parsing, validating, and formatting. To use libphonenumber, you’ll first need to install it using Composer.

composer require giggsey/libphonenumber-for-php

Format national phone numbers in PHP using libphonenumber

Once you have libphonenumber installed, you can use it to format phone numbers using the format() method.

<?php

require_once('vendor/autoload.php'); // Load the library

use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberType;
use libphonenumber\PhoneNumber;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberProto = $phoneUtil->parse('1234567890', 'US'); // Parse the phone number

$formattedNumber = $phoneUtil->format($numberProto, PhoneNumberFormat::NATIONAL); // Format the phone number

echo $formattedNumber; // (123) 456-7890

?>

In this example, we’re using libphonenumber to format a phone number in the United States. The parse() method is used to convert the phone number to a standardized format, and then the format() method is used to format the phone number according to the PhoneNumberFormat::NATIONAL format.

Format international phone numbers in PHP using libphonenumber

Here’s an example code snippet that uses the libphonenumber library to format an international phone number in PHP.

<?php

require_once('vendor/autoload.php'); // Load the library

use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberType;
use libphonenumber\PhoneNumber;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberProto = $phoneUtil->parse('+441632960961', 'GB'); // Parse the phone number

$formattedNumber = $phoneUtil->format($numberProto, PhoneNumberFormat::INTERNATIONAL); // Format the phone number

echo $formattedNumber; // +44 1632 960961

?>

The example is pretty much the same, except that the format() method is used to format the phone number in international format (i.e., with the country code included).

Benefits | Format phone numbers in PHP using preg_match() 

Here are some benefits of using the libphonenumber library to format phone numbers in PHP.

  1. The libphonenumber library supports phone numbers for various countries and regions and can format them in their respective formats. 
  1. The library consistently formats phone numbers across different countries and regions.
  1. The library includes validation features that can check if a phone number is valid for a specific region or country, reducing the risk of invalid phone numbers.
  1. The library provides a simple, easy-to-use API for formatting and validating phone numbers.
  1. The library allows customization of formatting and validation rules for specific regions or countries.

Overall, using the libphonenumber library can help ensure that phone numbers are handled correctly and consistently in your PHP application, reducing errors and improving the user experience.

Frequently Asked Questions

Should I store phone numbers in a specific format in my database?

It’s generally a good practice to store phone numbers in a consistent format in your database. This can help with data consistency, data validation, and data retrieval.

Here are a few things to consider when deciding on a format for storing phone numbers.

  1. You should include the country code as part of the phone number, as this is essential for making international calls.
  2. If the phone number is for a landline, you may want to include the area code as part of the phone number.
  3. You can choose to use separators (such as hyphens or parentheses) to make the phone number more readable. However, be consistent with the format you choose.
  4. Make sure to validate the phone numbers as they are entered into the database to ensure they are in the correct format.

Ultimately, the format you choose will depend on your specific use case and the needs of your application. However, storing phone numbers in a consistent format can help with data integrity and data retrieval.

How to handle exceptions when formatting phone numbers in PHP?

When formatting phone numbers in PHP, it’s important to handle exceptions that may occur. Here are some tips on how to handle exceptions:

  1. Check if the phone number is valid before formatting it. If the phone number is not valid, display an error message to the user.
  2. Handle exceptions related to formatting, such as if the phone number is in an unexpected format. You can use a try-catch block to catch these exceptions and display an error message to the user.
  3. Handle exceptions related to the phone number itself, such as if the phone number is invalid or does not exist. Again, use a try-catch block to catch these exceptions and display an appropriate error message.

By handling exceptions properly, you can ensure that your application does not crash or behave unexpectedly when formatting phone numbers. Instead, you can provide a smooth and error-free user experience.

What are the best practices for formatting phone numbers in PHP?

Here are some best practices to follow when formatting phone numbers in PHP.

  1. Validate the phone number before formatting it. Ensure that it is in the correct format and contains only digits. This will help prevent errors when formatting the phone number.
  2. Use a consistent format for all phone numbers. Decide on a standard format for phone numbers and stick to it throughout your application. This will make it easier for users to enter phone numbers correctly and for your application to process them.
  3. Strip any non-numeric characters before formatting the phone number. This includes characters such as spaces, dashes, and parentheses. Only keep the digits in the phone number to ensure consistent formatting.
  4. Use a formatting function or library to handle the formatting. Do not try to format phone numbers in your application code manually. Instead, use a formatting function or library to ensure the formatting is consistent and error-free.
  5. Provide a way for users to enter phone numbers in a standard format. You can use input masks or other input validation techniques to ensure that users enter phone numbers correctly. This will help prevent errors and make it easier to format phone numbers correctly.

By following these best practices, you can ensure that phone numbers are formatted correctly in your PHP application and that the user experience is smooth and error-free.

How to Format Phone Numbers in PHP

There are three different ways to format phone numbers in PHP. You can use the substr() function, preg_match(), and the libphonenumber library. Each section includes an explanation of the code followed by a code example. 

The article also covers best practices and handling exceptions when formatting phone numbers in PHP. The article is an excellent resource for developers who must format phone numbers in their PHP projects.
That’s it for now. Stay tuned for more at FuelingPHP.

Article series on Phone Communication

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.