Skip to content

Format Phone Number using PHP

Last updated on April 23, 2018

Below is a tiny function that will take any 10 digit number and convert it into the following phone format: 970-313-2428.


function phone_number_format($number) {
  // Allow only Digits, remove all other characters.
  $number = preg_replace("/[^\d]/","",$number);
 
  // get number length.
  $length = strlen($number);
 
 // if number = 10
 if($length == 10) {
  $number = preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);
 }
  
  return $number;

}

That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments