Skip navigation

I wrote a function today to format user phone numbers to “xxx xxx-xxx”.  If anyone has a better way of doing this, I’d love to hear it.  For instance, I’d like to know how to insert a character into a certain location inside a string.  As it is, I had to split the string up in order to add whitespace or hypens. 

//function to format US phone numbers to xxx xxx-xxxx
function FormatPhone($Input){
   //trim whitespace off ends
   $Input = trim($Input);

   //trim out whitespace from between numbers
   $Input = str_replace(” “,””,$Input);

   //trim out all characters that are not integers
   $Input = ereg_replace(“[^0-9]”,””,$Input);

   //Count all characters
   $CharCount = strlen($Input);

   //if length is greater than 10, just take last 10 digits
      //trim off all but last 10 digits
     $Input = substr($Input, -10);

   //FORMAT number
   //split area code out
   $AreaCode = substr($Input,0,3);

   //add whitespace to the end of area code
   $AreaCode = str_pad($AreaCode, 4);

   //split out prefix and suffix
   $Prefix = substr($Input,3,3);
   $Suffix = substr($Input,6);

   //add hypen to prefix
   $Prefix = str_pad($Prefix, 4, ‘-‘, STR_PAD_RIGHT);

   //add it all up
   $PhoneNum = $AreaCode.$Prefix.$Suffix;

   //return the new phone number
   return $PhoneNum;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: