A function written by Julius Davies, an old friend of mine who’s actually responsible for getting me into programming in the first place. He’s posted a demonstration of this function on his site, here.

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
   Takes a string (hopefully containing digits), strips
   out all garbage, and returns it as a nicely formatted
   phone number.

   cleanPhoneString("6042513219")          returns:  "604-251-3219"
   cleanPhoneString("60425132191234")      returns:  "604-251-3219 x 1234"
   cleanPhoneString("6a0b4c2d5e1f3g2h1i9") returns:  "604-251-3219"

   This method is meant to be used hand-in-hand with "isValidPhoneString()".

   Example usage:

       $cleanPhone = cleanPhoneString( $str );
       if ( !isValidPhoneString( $cleanPhone ) )
       {
         $cleanPhone = "invalid!";
       }
*/

function cleanPhoneString( $phoneStr )
{
  $len = strlen( $phoneStr );
  $buf = "";
  for ( $i = 0; $i < $len; $i++ )
  {
    $c = $phoneStr{$i};
    if ( ctype_digit( $c ) )
    {
      $buf = $buf.$c;
    }
  }
  $phoneStr = $buf;
  $len = strlen( $phoneStr );
  $buf = "";
  for ( $i = 0; $i < $len; $i++ )
  {
    $c = $phoneStr{$i};
    if ( ctype_digit( $c ) )
    {
      if ( $i == 3 || $i == 6 )
      {
        $buf = $buf."-";
      }
      else if ( $i == 10 )
      {
        $buf = $buf." x ";
      }
      $buf = $buf.$c;
    }
  }
  return $buf;
}

/*
   Tests to make sure string is a valid phone number.  You should first
   run your string through cleanPhoneString() first, since isValidPhoneString()
   depends on the formatting provided by cleanPhoneString().
*/

function isValidPhoneString( $phoneStr )
{
  $l = strlen( $phoneStr );
  $c = "";
  if ( $l >= 1 )
  {
    $c = $phoneStr{0};
  }
  // Must be at least 12 digits (xxx-xxx-xxxx), and must
  // not start with 0 or 1.  Must not be more than 20 digits
  // (xxx-xxx-xxxx x xxxxx).
  return $l >= 12 && $l <= 20 && $c != '0' && $c != '1';
}