分割数据时不使用分隔符?
好吧,假设我的电话号码存储在表中为:
“0008675309”,
我显然不想这样显示它,我想在调用它时将其格式化为:
(000)867-5309
可以吗最好使用 / - 或 等分隔符将其存储在数据库中。这样我以后就可以分开了?或者可以按字符数来分割吗?
Ok say I have my phone numbers stored in my table as:
"0008675309"
I obviously wouldn't want to display it just like that, I'd want to format it when I call it as:
(000)867-5309
Would it be better to store it in the database with a delimiter such as / - or . So that I can split it later? Or is it possible to split it by the number of characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
处理任何这些格式的电话号码的性能成本和代码都很简单,因此这实际上取决于您的偏好。要回答您的问题,可以很容易地获取前三个字符、接下来的三个字符和最后四个字符,例如使用
substr
函数。The performance cost and code to process a phone number in any of those formats is simple, so it's really up to your preference. To answer your question, it is very easy to grab the first three characters, the next three, and the last four using for example,
substr
function.这是一个可以完成您想要的操作的单行代码:
作为一项额外的好处,如果输入格式不匹配(国际数字),它不会更改格式。
Here is a one liner that does what you want:
As a added bonus it won't change the format if the input format doesn't match (international numbers).
如果您只存储北美电话号码(10 位数字),那么正如 @mellamokb 指出的那样,无论哪种方式都可以。如果您可能存储国际号码,则应尽早(如果可能)捕获尽可能多的详细信息,因为以后可能很难知道如何对号码进行标点符号。
If you are only storing North American phone numbers (10 digits), then as @mellamokb noted, you're ok either way. If you may be storing international numbers, you should capture as much detail as you can early on (if possible) since it might be hard to know how to punctuate the number later on.
将 preg_split 与 PREG_SPLIT_NO_EMPTY 一起使用
use preg_split with PREG_SPLIT_NO_EMPTY
其他答案是完全正确的。如果您想要它的实际代码,我认为以下应该可以解决问题(索引可能会偏离一个哎呀!):
The other answers are perfectly correct. In case you wanted the actual code for it, I think the following should do the trick (the indexes may be off by one oops!):