拆分php中的电话号码 [英] Splitting up a phone number in php

查看:186
本文介绍了拆分php中的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个变量$ phone,其中包含字符串(407)888-9999,我有这个代码

Ok so i have a variable $phone which contains the string (407)888-9999 and I have this code

 if($phone != ''){ $phone = "<span id='telephone'>{$phone}</span>";}
return $phone;

这很好,但现在客户端想要在区域代码和下一个区域代码之间有一些填充三个数字。所以我需要的代码是这样

This works fine but now the client wants to have a some padding in between the area code and the next three numbers. So i need the code to be like this

<span id='telephone'><span class='spacer'>(407)</span>888-9999</span>";


推荐答案

没有其他人提到这一点,我会从数字中除去所有的非数字字符。一旦完成,你可以使用正则表达式很容易获得数字,这种方式任何格式是有效和漂亮无论用户输入什么,您都可以按照自己的需要设置格式:

Given no one else mentioned this, I would strip out all non-numeric characters from the number. Once done you can use a regex to easily get the numbers, this way any format is valid and pretty much no matter what the user enters you can format it how you want it:

$phone = preg_replace("~[^0-9]~", "", $phone);
preg_match('~([0-9]{3})([0-9]{3})([0-9]{4})~', $phone, $matches);

if (!empty($matches)) {
    $display = "<span id='telephone'><span class='spacer'>(" . 
                $matches[1] . ")</span>" . $matches[2] . "-" . $matches[3] . "</span>";
}else {
    $display = "An invalid phone number was entered.";
}

无论如何输入电话号码,只要有10位数字。

Should do it not matter how the phone number is entered as long as there are 10 digits.

UPDATE

您也可以使用 preg_replace substr 并放弃 preg_match 的需要这实际上是我的首选解决方案。

You could also use the preg_replace technique with substr and forego the need for preg_match. This would actually be my preferred solution.

$phone = preg_replace("~[^0-9]~", "", $phone);

if (strlen($phone) == 10) {
    $display = "<span id='telephone'><span class='spacer'>(" . 
                substr($phone,0,3) . ")</span>" . substr($phone,2,3) . "-" . substr($phone,5,4) . "</span>";
}else {
    $display = "An invalid phone number was entered.";
}

这篇关于拆分php中的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆