PHP script to properly format phone numbers

Summary: One of the biggest challenges as a programmer lies in the fact that you have to think ahead for your users so that things work seamlessly.  On any site involving input fields that interact with a database, it is critical that the information be validated before going into the database, and with a bit of forethought you can make sure that the inputs are not only valid, but in a standardized format.

Consider phone numbers as an example.  If you ask 10 people to write down their phone numbers, you might get several different responses:

  • 555.5555
  • 555-5555
  • 555.555.5555
  • 555-555-5555
  • (555)555.5555
  • (555)555-5555
  • 5555555
  • 5555555555
  • 1.555.555.5555
  • 1-555-555-5555
  • 1(555)555.5555
  • 1(555)555-5555
You get the idea.
 
Concept:  While you could write code that forces users to type in the phone number a certain way, you can also just code better and with your user in mind to allow them to enter it however they want.  For many local businesses, it may not be necessary at all to have an area code so why demand this?
Problem: I searched for a long time, but could not find an open-source PHP script that would automatically format a phone number for me that would handle all these various input types.  So I went ahead and wrote it and am posting it on here for whoever may find use in it.

Difficulty Level: Super Easy (just upload this code your the server and pass in the phone number as the only parameter)
Prerequisites: To do this you must have access to a local or remote server that can process the script.
Implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function formatPhone($input){
    $l=strlen($input);
    if($l==8){// check for ###-#### or ###.####
        if(strpos($input,"-") != false) {//This is redundant since I put it right back, but hey you can take and modify this however you want
            $FixedPhone = $input;
        } elseif(strpos($input,".") != false) {//This is important because I don't want periods in the phone numbers
            $phoneChunks = explode(".", $input);
            $FixedPhone = $phoneChunks[0]."-".$phoneChunks[1];//Concatenate the two pieces together
        }
    }elseif($l==7){//Check for #######
        $input=str_split($input);
        $FixedPhone=$input[0].$input[1].$input[2]."-".$input[3].$input[4].$input[5].$input[6];//Concatenate digit by digit
    }elseif(strpos($input,")") != false) {//Check for the ')' bracket, I assume that if this exists then the first part '(' also is there.
            if(strpos($input,"-") != false) {
                $phoneChunks = explode("-", $input);
            } elseif(strpos($input,".") != false) {
                $phoneChunks = explode(".", $input);
            }
            $phoneChunks[0]=preg_replace("/[^0-9()]/", "", $phoneChunks[0]);//
            $FixedPhone=$phoneChunks[0]."-".$phoneChunks[1];
    }elseif($l==10){
                $input=str_split($input);//Split and concatenate digit by digit
                $FixedPhone="(".$input[0].$input[1].$input[2].")".$input[3].$input[4].$input[5]."-".$input[6].$input[7].$input[8].$input[9];
    }else{
        if(strpos($input,".") != false) {
            $input=preg_replace("/[^.]/", "-", $input);
        }
        $phoneChunks = explode("-", $input);
        if(strlen($phoneChunks[0])==5){
            $phoneChunks[0]=preg_replace("/[^0-9]/", "", $phoneChunks[0]);
        }
        $FixedPhone = "(".$phoneChunks[0].")".$phoneChunks[1]."-".$phoneChunks[2];
    }
    if($FixedPhone!="()-"&&$FixedPhone!="-"){
        return $FixedPhone;
    }
}

Explanation: First, it is assumed that this is for formatting an input only and NOT for validation in any way shape or form. I already have separate validation scripts that check for malicious code and non-numeric characters. The comments should speak for themselves.

 

Summary: I am aware that there are probably 100 other ways to do this and that this code can be enhanced. Also, I don’t claim that there isn’t someone out there who could manage to enter a phone number in such a way that this function won’t even work on, but at least it is a pretty good start for 99.999% of the people out there. Do you have any questions, comments, or ideas to improve this code? If so, drop me a line here and let me know.

About Andrew Turner (aka Arcitech)