Forums

PHP

This topic is locked

format a phone number

Posted 19 Dec 2006 17:51:50
1
has voted
19 Dec 2006 17:51:50 Bill Brandes posted:
I have a $Phone field in a database table that is 10 digits. 0123456789

I would like to easily format it for output in html to read (012) 345-6789

Can anyone please help?

Thanks,

Bill

Replies

Replied 20 Dec 2006 19:12:58
20 Dec 2006 19:12:58 Alan C replied:
convert the number to text - function strval converts numbers to text strings

check length using strlen function and then use str_pad function to put in the leading zero

you will now have a string of length 10

how you then chop the string and insert the other characters is down to your personal coding style, I would use the substr function to slice up the 10 digits and insert the other bits, every coder will tell you to do it a different way and will back that up with good reasons for doing it that way.

Browse the php functions list too - it's a great resource, good examples included

ca3.php.net/manual/en/function.substr.php
Replied 21 Dec 2006 03:33:04
21 Dec 2006 03:33:04 Bill Brandes replied:
Thanks Alan,

Easiest solution i came up with is this:

$AreaCode = substr($Phone, 0, 3); // returns "012";
$Prefix = substr($Phone, 3, 3); // returns "345";
$LastFour = substr($Phone, 6, 4); // returns "6789"

You would think you could search and find on the search engines something so easy. After hours and hours of wasting time. Well at least it works fine.

Thanks again,

Bill

Edited by - gibsongk55 on 21 Dec 2006 05:32:54
Replied 21 Dec 2006 11:39:36
21 Dec 2006 11:39:36 Roddy Dairion replied:
That will cause a problem if someone do something like 345-6789. Enter 3 fields Area code, Prefix and Last four. Like that no mistake will be made.

Edited by - roders22 on 21 Dec 2006 11:41:09

Reply to this topic