Friday, October 10, 2025
HomeLanguagesHow to format Phone Numbers in PHP ?

How to format Phone Numbers in PHP ?

In this article, we will learn how to format phone numbers using PHP. When we need to store a phone number then we store the formatting phone number. Using PHP, we can easily format phone numbers.

Approach: In this article, we will format the phone number using the preg_match() method. We can use this method to format phone numbers. This function has special characteristics of finding specified patterns from string. 

PHP code: The following is the complete code to format phone numbers using preg_match().

PHP




<?php
  
// Create a formatting function
function formatting($phone){
      
    // Pass phone number in preg_match function
    if(preg_match(
        '/^\+[0-9]([0-9]{3})([0-9]{3})([0-9]{4})$/', 
    $phone, $value)) {
      
        // Store value in format variable
        $format = $value[1] . '-' . 
            $value[2] . '-' . $value[3];
    }
    else {
         
        // If given number is invalid
        echo "Invalid phone number <br>";
    }
      
    // Print the given format
    echo("$format" . "<br>");
}
   
// Call the function
formatting("+02025550170");
  
formatting("+01677942758");
?>


Output:

202-555-0170
167-794-2758
RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS