format phone number

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
calebsg
Forum Commoner
Posts: 28
Joined: Tue Jun 18, 2002 10:41 am

format phone number

Post by calebsg »

How can I format a string from a database like 9876543210 to appear as 987-654-3210? I am unfamiliar with regular expressions and not sure where to start.
will
Forum Contributor
Posts: 120
Joined: Fri Jun 21, 2002 9:38 am
Location: Memphis, TN

Post by will »

actually you wouldn't need to use regex for this... the simple string functions will do it....

Code: Select all

$phone = 1234567890;

$newphone = substr($phone,0,3) . '-' . substr($phone,3,3) . '-' . substr($phone,6,4);
you would need to check and make sure the number is ten digits though, or else it'd get a little messed up. something like (strlen($phone)==10)
Post Reply