I have a phone number that is stored in a database like:
5555555555
I want to format this like:
(555) 555-5555
using php i have the following code:
<?php
$data = $order['contactphone'];
if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
echo $result;
}
?>
This returns nothing at all once so ever. Not even an error. How can I do this?
This is what I've used in the past. Not as elegant as a regex I suppose but it can get the job done:
/**
* Formats a phone number
* @param string $phone
*/
static public function formatPhoneNum($phone){
$phone = preg_replace("/[^0-9]*/",'',$phone);
if(strlen($phone) != 10) return(false);
$sArea = substr($phone,0,3);
$sPrefix = substr($phone,3,3);
$sNumber = substr($phone,6,4);
$phone = "(".$sArea.") ".$sPrefix."-".$sNumber;
return($phone);
}
ps I didn't write this, just something I grabbed six years ago.
Change regex from '/^\\+\\d(\\d{3})(\\d{3})(\\d{4})$/'
to '/^(\\d{3})(\\d{3})(\\d{4})$/'
, ie:
if( preg_match( '/^(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = '(' . $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
echo $result;
}
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.