class PhoneNumber { private function clean($phone){ //$clean_phone = preg_replace("^[a-zA-Z._%-+-()]^",'',$phone); //remove all non digit charactures from the phone number. $clean_phone = preg_replace("[\D]",'',$phone); // Make sure 1 isn't the first number. if($clean_phone[0] == 1){$clean_phone = substr($clean_phone,1,10);} // See if it's a 9 digit number. if(strlen($clean_phone) != 10){echo "Error: Parsing Invalid Phone Number."; exit();} // Send back all the plain digits. return $clean_phone; } public function formatted($style,$phone){ switch($style){ case 0: // (xxx) xxx-xxxx return "(".$this->areacode($phone).") ".$this->prefix($phone)."-".$this->last4digits($phone); break; case 1: // xxx-xxx-xxxx return $this->areacode($phone)."-".$this->prefix($phone)."-".$this->last4digits($phone); break; case 2: // xxx.xxx.xxxx return $this->areacode($phone).".".$this->prefix($phone).".".$this->last4digits($phone); break; case 3: // xxx xxx-xxxx return $this->areacode($phone)." ".$this->prefix($phone)."".$this->last4digits($phone); break; default: // xxxxxxxxxx return $this->digits($phone); break; } } public function areacode($phone){ return substr($this->clean($phone),0,3); } public function prefix($phone){ return substr($this->clean($phone),3,3); } public function last4digits($phone){ return substr($this->clean($phone),6,4); } public function digits($phone){ return $this->clean($phone); } }