Blog

Newest Post
Blog Archives
Blog Categories

Portfolio

3D Models
Banners
Brochures
Business Cards
Custom Programming
Environments
Flash Projects
Game Design
Image Altering
Web Design

About

Resume
Recommendation Letters

Contact

February 9, 2009

Format Phone Number Fields with PHP

Filed under: PHP,The Coding World — admin @ 1:39 pm

Below is a function I wrote to take a phone number entered by a user and convert it into a desired format. The one shown below is 555-555-5555.

function phn_numb($numb) {
if (!is_numeric(substr($numb, 0, 1)) && !is_numeric(substr($numb, 1, 1))) { return $numb; }
 
$chars = array(' ', '(', ')', '-', '.');
$numb = str_replace($chars, "", $numb);
if (strlen($numb) > 10) {
//you must dial "1" before dialing this number
$numb = substr($numb, 0, 1).'-'.substr($numb, 1, 3).'-'.substr($numb, 4, 3).'-'.substr($numb, 7, 4);
}
else
{
$numb = substr($numb, 0, 3).'-'.substr($numb, 3, 3).'-'.substr($numb, 5, 4);
}
 
return $numb;
}

Therefore to see it in action:

$phonenumber = 2345678901;
 
echo phn_num($phonenumber);
 
//the resulting echo would be 234-567-8901

Leave a Reply

© - Digital Epiphany Designs, Online Portfolio for Web Design, Custom Programming, Grapic Design and Game Design.