Php – format and display a phone number on a report page in PHP

phone-numberphp

I have a database field called customer_phone that is stored as it was inputted. It is displayed on a report page now from the database like this:

print  "Phone: $customer_phone<br>";

I'd like to get the data from the database field, strip out any extra characters if any to just numbers (ex: xxx-xxx-xxxx to xxxxxxxxxx) and then display it on the page in this format:

(xxx) xxx-xxxx

I've found function scripts to do this but haven't been able to get them to work.

I need to get the data from the database field, re-format it and display it on the page.

I'm a PHP newby and would appreciate any help.

Best Solution

function format_telephone($phone_number)
{
    $cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
    preg_match('/(\d{3})(\d{3})(\d{4})/', $cleaned, $matches);
    return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
}

There's a function to do as you asked, call it like

<?php echo format_telephone($customer_phone); ?>
Related Question