[英]Format a phone number with PHP
In the database i have a field in the customers table called customers_telephone. 在数据库中,客户表中有一个名为customers_telephone的字段。 i want the output the telephone number like this(555) 555-5555.
我想要输出这样的电话号码(555)555-5555。 within this CMS (oscommerce) the output on invoice.php looks like this.
在此CMS(oscommerce)中,invoice.php的输出如下所示。
<td class="main"><?php echo $order->customer['telephone']; ?></td>
i found a code that may work: 我发现了可能有效的代码:
<?php
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]}";
}
?>
<?php echo format_telephone($customer_phone); ?>
but i am confused where to place this and what variables to insert, i only need the format, only here and for US phones only. 但是我很困惑将其放置在何处以及要插入哪些变量,我只需要格式,仅在这里和仅适用于美国电话。
You can use regular expression 您可以使用正则表达式
$phone_numbers = array(
'555-555-5555',
'5555425555',
'555 555 5555',
'1(519) 555-4444',
'1 (519) 555-4422',
'1-555-555-5555',
'1-(555)-555-25555',
);
$regex = "/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i";
foreach( $phone_numbers as $number ) {
echo $number . ': ' . ( preg_match( $regex, $number ) ? 'valid' : 'invalid' ) . '<br/>';
}
555-555-5555: valid
5555425555: valid
555 555 5555: valid
1(519) 555-4444: valid
1 (519) 555-4422: valid
1-555-555-5555: valid
1-(555)-555-5555: valid
1-(555)-555-25555: invalid
That's ok. 没关系。
In Invoice.php file make sure you have this following block of code before you use it in the <td
在Invoice.php文件中,在
<td
使用它之前,请确保具有以下代码块
<?php
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]}";
}
?>
So put his line of code above somewhere, then in this line of code make sure you have 因此,将他的代码行放在某个位置的上方,然后在此代码行中确保您拥有
<td class="main"><?php echo format_telephone($order->customer['telephone']); ?></td>
That's it. 而已。 You need to have the function before you use it on the code.
在代码上使用该功能之前,需要先具有该功能。 Let us know if you have additional issues.
让我们知道您是否还有其他问题。
If you have code for a function, for example: 如果您有函数的代码,例如:
<?php
function hello($hi) {
return($hi);
}
echo(hello("hey"));
?>
This would echo 'hey'. 这会回声“嘿”。
Anyway, now to the point: you would want to run the following to echo the phone number. 无论如何,现在到了要点:您可能需要运行以下命令以回显电话号码。
<td class="main"><?php echo format_telephone($order->customer['telephone']); ?></td>
Make sure that you add the function code before you try and call it! 在尝试调用之前,请确保添加了功能代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.