[英]Format Phone Number in PHP
I have a phone number that is stored in a database like: 我有一个存储在数据库中的电话号码,例如:
5555555555 5555555555
I want to format this like: 我想这样格式化:
(555) 555-5555 (555)555-5555
using php i have the following code: 使用PHP我有以下代码:
<?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. ps我没有写这个,只是我六年前抓到的东西。
Change regex from '/^\\+\\d(\\d{3})(\\d{3})(\\d{4})$/'
to '/^(\\d{3})(\\d{3})(\\d{4})$/'
, ie: 将正则表达式从
'/^\\+\\d(\\d{3})(\\d{3})(\\d{4})$/'
更改为'/^(\\d{3})(\\d{3})(\\d{4})$/'
,即:
if( preg_match( '/^(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = '(' . $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
echo $result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.