Link to home
Start Free TrialLog in
Avatar of cookmyster
cookmysterFlag for Canada

asked on

Formatting Phone Number

Hello...

I am using PHP and an Access Database..   i have phone numbers in the databases.....

this is the format of phone number    3135551234
thiis is  the format I need  (313)555-1234

Any ideas how I can do that??

Thx
Rich
Avatar of Andy
Andy
Flag of United Kingdom of Great Britain and Northern Ireland image

Phone numbers here in the UK vary in length but if over there they are always (3 digits)3digits-4digits then you could do this...

$number = "3135551234";
$part1 = substr($number,0,3);
$part2 = substr($number,3,3);
$part3 = substr($number,6,4);
$format = "(%s)%s-%s";
$result = sprintf($format,$part1,$part2,$part3);
echo $result;
Avatar of robinet02
robinet02

using regexp functions :

$phone_number = "3135551234";
$phone_number = preg_replace("/(\d{3})(\d{3})(\d{4})/", "(\$1)\$2-\$3", $phone_number);

print $phone_number will now output : (313)555-1234


Avatar of cookmyster

ASKER

Hi...

Your formatting works great..one problem...    I am bringing the phone number out from a database....so I am not sure where to put the replace formatting???

Here is my code...


$result = mysql_query("select tb_name, tb_address1, tb_phonenumber from tricity_business where tb_name like '%$txtname%' and tc_id = $selcity", $linkID);


                  while ($row = mysql_fetch_row($result))
                  {
                        print"<tr>";
                        foreach($row as $field)
                        {
                              print "<td>$field</td>";
                        }
                        print "</tr>";
                  }

Thx,
Rich
ASKER CERTIFIED SOLUTION
Avatar of robinet02
robinet02

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial