PHP Change Phone Numbers Format Example


Share:
 | Published By: Admin | Published On: Jan 17, 2022 | Category: PHP

Hello Dev,

Now let's see example of how to use phone numbers format in php? , I explained simply about phone numbers format in php? , I am going to show you numbers format php , We will learn use phone numbers format.

In this post, You'll learn change phone numbers format example , This article will give you example of formula to change phone number format in php preg_replace.

So let's see bellow example:

Example : 1
<?php

    function phone_number_format($number){

        // Allow only Digits, remove all other characters.
        $number = preg_replace("/[^\d]/","",$number);
     
        // get number length.
        $length_of_number = strlen($number);
     
        // if number = 10
        if($length_of_number == 10) {
            echo $number = "Mobile Number is : " . preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);
        }else{
            echo "Invalid Number";
        }

    }

    phone_number_format(9423908056);

?>
Output:
Mobile Number is : 942-390-8056
Example : 2
<?php 

    $data = '+11234567890';

    if(preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches ) )
    {
        $result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
        echo "Mobile Number is : ".$result;

    }else{
        echo "Invalid Number";
    }

?>
Output:
Mobile Number is : 123-456-7890
I hope it can help you...
Share: