如何将10位数的字符串格式化为电话号码? [英] How do you format a 10 digit string into a phone number?

查看:103
本文介绍了如何将10位数的字符串格式化为电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10个字符长的字符串形式的数据库记录,例如4085551234.

I have database records in the form of 10 character long strings, such as 4085551234.

我希望将其格式化为以下格式:(408)555-1234.

I wish to format these into this format: (408) 555-1234.

我认为这与正则表达式有关.我是编程新手,在这里完全是自学成才的,因此,与执行文本处理有关的任何资源也将不胜感激.谢谢!

I think this is regex related. I'm new to programming and completely self-taught here, so any sort of resource relating to performing text processing would be appreciated as well. Thanks!

推荐答案

使用正则表达式绝对可以解决这个问题.如果您想获取一个电话号码"并将其标准化为10位数字,那么这对于正则表达式将是一个很好的用法.要执行您的要求,只需执行以下操作即可:

A regex is definitely overkill for this one. If you wanted to take a "phone number" and normalize it to 10 digits, that would be a good use for a regex. To do what you're asking, just do something like:

echo '('.substr($data, 0, 3).') '.substr($data, 3, 3).'-'.substr($data,6);

由于您已经知道如何分割数据,因此只需使用substr或类似方法即可获取所需的部分. RegEx可用于匹配并非总是具有严格格式的字符串. (例如可变数量的空格,可变字符之前或之后,多余的破折号等).但是,在您的情况下,输入始终严格采用10位数格式,因此,您不需要RegEx的额外开销即可对其进行格式化.

Since you already know how to divide up your data, you can just use substr or something similar to grab the parts you want. RegEx is useful for matching strings which don't always have a strict format. (Like variable numbers of spaces, variable stuff before or after it, extra dashes, etc). But in your case the input is always strictly formatted 10 digits, nothing else, so you don't need the extra overhead of a RegEx to format it.

这篇关于如何将10位数的字符串格式化为电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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