Browse by Month RSS Feed
  • August 2010
  • July 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010

  • function: cleanPhoneString()December 9, 2006
    Filed under: Code, PHP @ 4:57 pm

    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.

    /*
       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';
    }

    Comments (0)

    No Comments »

    No comments yet.

    RSS feed for comments on this post. TrackBack URI

    Leave a comment