电话号码与字母的正则表达式
我需要将电话号码格式化为一长串数字(美国电话号码格式)
// I know there are tons more
$phones = array(
'1(800) 555-1212',
'1.800.555.1212',
'800.555.1212',
'1 800 555 1212',
'1.800 CALL NOW' // 1 800 225-5669
);
foreach($phones as $phone) {
echo "new format: ".(preg_replace("/[^0-9]/", "", $phone)."<br />\n";
}
现在应该返回类似这样的内容:
8005551212 (with or without the 1)
但是如何使用 CALL NOW 将号码映射/转换为:
18002255669
I need to format a phone number as one long string of numbers (US Phone Number format)
// I know there are tons more
$phones = array(
'1(800) 555-1212',
'1.800.555.1212',
'800.555.1212',
'1 800 555 1212',
'1.800 CALL NOW' // 1 800 225-5669
);
foreach($phones as $phone) {
echo "new format: ".(preg_replace("/[^0-9]/", "", $phone)."<br />\n";
}
Now this should return something like this:
8005551212 (with or without the 1)
but how do I map/convert the number with CALL NOW to:
18002255669
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了节省一些打字...
To save some typing...
您可以使用
strtr()
。或者实际上,我认为:
You could use
strtr()
.Or actually, I think:
第一步,您需要执行不同的正则表达式替换(您的版本现在将丢失所有字母):
然后,您需要获取字符串并将每个字母替换为其相应的数字(请参阅konforce的答案)。这并不是正则表达式真正的工作。
For the first step, you need to do a different regex replace (your version would now lose all the letters):
Then, you need to take the string and replace each letter with its corresponding digit (see konforce's answer). That's not really a job for a regex.