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.
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); ?>
$phone_number= preg_replace('/[^0-9]+/', '', $phone_number); //Strip all non number characters
echo preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone_number) //Re Format it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.