PHP Format Phone Number Function

Below is a short function that will take any 10 or 9 digit number and convert it into the following phone format: 555-555-5555

<?php
function phn_numb($numb) {
  if (!is_numeric(substr($numb, 0, 1))  && !is_numeric(substr($numb, 1, 1))) { return $numb; }
 
  $chars = array(' ', '(', ')', '-', '.');
  $numb = str_replace($chars, "", $numb);
 
  if (strlen($numb) > 10) {
    // a 10 digit number, format as 1-800-555-5555
    $numb = substr($numb, 0, 1) . '-' . substr($numb, 1, 3) . '-' . substr($numb, 4, 3) . '-' . substr($numb, 7, 4);
  }
  else {
    $numb = substr($numb, 0, 3) . '-' . substr($numb, 3, 3) . '-' . substr($numb, 5, 4);
  }
 
  return $numb;
}
 
// Example
 
$phonenumber = 2345678910;
 
echo phn_num($phonenumber); //result 234-567-8910
?>

Tags: