www.burnmytime.com // $phone_number can be any format. ex: (555)555.5555 15555555555 555-555-555 1-555-555-5555 $phone = new PhoneNumber(); $phone->areacode($phone_number); // returns the area code of the phone number. $phone->prefix($phone_number); // returns the prefix of the phone number. $phone->number($phone_number); // returns the last four digits of the phone number. $phone->last4digits($phone_number); // returns entire phone number just digits. $phone->formatted(int[0-3],$phone_number); // returns phone number pre-formatted. // Formats. // 0 (xxx) xxx-xxx // 1 xxx-xxx-xxxx // 2 xxx.xxx.xxx // 3 xxx xxxxxx */ 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); } } // TESTS.. REMOVE EVERYTHING BELOW THIS. //$myphone = "5551112532"; //$myphone = "(555)111-2532"; //$myphone = "(555) 111_2532"; //$myphone = "555.111.2532"; $myphone = "1(555)_ejsz&%111-2532*"; $phone = new PhoneNumber(); echo $phone->areacode($myphone)."
"; echo $phone->prefix($myphone)."
"; echo $phone->last4digits($myphone)."
"; echo $phone->digits($myphone)."
"; echo $phone->formatted(0,$myphone)."
"; echo $phone->formatted(1,$myphone)."
"; echo $phone->formatted(2,$myphone)."
"; echo $phone->formatted(3,$myphone)."
"; ?>