Set phone number formatting in PHP

To display formatted phone number using php you can use this function.
It consist of 5 patterns for numbers that can be easily changed to format what you need.
First pattern for 6 numbers: XX-XX-XX
Second pattern for 7 numbers: XXX-XXXX
Third pattern for 10 numbers: (XXX) XXX-XXXX
Fourth pattern for 12 numbers: +XXX (XX) XX-XX-XXX
Fifth pattern for 13 numbers: +XXX (XX) XXXX-XXXX

function getFormatedPhone($phone_number='')
{
	$phone = preg_replace("/[^0-9]/", '', $phone_number); //get only numbers
	$phone_length = strlen($phone);
	
switch ($phone_length) {
    case 6:
        $phone_formated = preg_replace("/([0-9]{2})([0-9]{2})([0-9]{2})/", "$1-$2-$3", $phone);
    break;
    case 7:
        $phone_formated = preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
    break;
    case 10:
        $phone_formated = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
    break; 
    case 12:
        $phone_formated = preg_replace("/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{3})/", "+$1 ($2) $3-$4-$5", $phone);
    break;
    case 13:
        $phone_formated = preg_replace("/([0-9]{3})([0-9]{2})([0-9]{4})([0-9]{4})/", "+$1 ($2) $3-$4", $phone);
    break;
    default:
        $phone_formated = $phone;
    break;	
	}
return $phone_formated;
}

for ( $i=0; $i<10; $i++)
{
    $test_random_phone_number = rand(0,1)?(rand(10,99).rand(10,99).rand(10,99)):(rand(0,1)?(rand(100,999).rand(100,999).rand(1000,9999)):(rand(100,9999).rand(10,99).rand(1000000,9999999)));
    echo $test_random_phone_number.' formated to: ';
    echo getFormatedPhone($test_random_phone_number);
    echo "<br/>";
}

Results ↓
Continue reading Set phone number formatting in PHP