分割数据时不使用分隔符?

发布于 2024-11-04 07:22:38 字数 167 浏览 1 评论 0原文

好吧,假设我的电话号码存储在表中为:

“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

在巴黎塔顶看东京樱花 2024-11-11 07:22:38

处理任何这些格式的电话号码的性能成本和代码都很简单,因此这实际上取决于您的偏好。要回答您的问题,可以很容易地获取前三个字符、接下来的三个字符和最后四个字符,例如使用 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.

樱桃奶球 2024-11-11 07:22:38

这是一个可以完成您想要的操作的单行代码:

$phone = preg_replace('^(\d{3})(\d{3})(\d{4})

作为一项额外的好处,如果输入格式不匹配(国际数字),它不会更改格式。

, '($1)$2-$3', $phone);

作为一项额外的好处,如果输入格式不匹配(国际数字),它不会更改格式。

Here is a one liner that does what you want:

$phone = preg_replace('^(\d{3})(\d{3})(\d{4})

As a added bonus it won't change the format if the input format doesn't match (international numbers).

, '($1)$2-$3', $phone);

As a added bonus it won't change the format if the input format doesn't match (international numbers).

小情绪 2024-11-11 07:22:38

如果您只存储北美电话号码(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.

聆听风音 2024-11-11 07:22:38

将 preg_split 与 PREG_SPLIT_NO_EMPTY 一起使用

use preg_split with PREG_SPLIT_NO_EMPTY

葬心 2024-11-11 07:22:38

其他答案是完全正确的。如果您想要它的实际代码,我认为以下应该可以解决问题(索引可能会偏离一个哎呀!):

$phone_number="0008675309"
$phone_number=substr_replace($phone_number, "(", 0, 0);
$phone_number=substr_replace($phone_number, ")", 4, 0);
$phone_number=substr_replace($phone_number, "-", 8, 0);

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!):

$phone_number="0008675309"
$phone_number=substr_replace($phone_number, "(", 0, 0);
$phone_number=substr_replace($phone_number, ")", 4, 0);
$phone_number=substr_replace($phone_number, "-", 8, 0);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文