PHP - 在字符串中间添加字符(从末尾开始)
如何在字符串中间添加字符?
我正在尝试将美国号码(例如 2121231234)格式化为带有破折号的号码,如下所示:212-123-1234。
我事先不知道这串数字有多长,
它可能是 12121231234,甚至可能是 0012121231234,
在这种情况下,我希望它分别变成 1212-123-1234 和 001212-123-1234。
到目前为止,这就是我的想法:
$phone_number = '2121231234';
$phone_number = str_split($phone_number); // [2,1,2,1,2,3,1,2,3,4]
$phone_number = array_reverse($phone_number); // [4,3,2,1,3,2,1,2,1,2]
array_splice($phone_number, 4, 0, '-'); // [4,3,2,1,-,3,2,1,2,1,2]
array_splice($phone_number, 8, 0, '-'); // [4,3,2,1,-,3,2,1,-,2,1,2]
$phone_number = array_reverse($phone_number); // [2,1,2,-,1,2,3,-,1,2,3,4]
$phone_number = implode($phone_number); // "212-123-1234"
可行,但对于完成如此简单的任务来说似乎太多了。
我缺少什么?
How do you add characters in middle of a string?
I'm trying to format a US number such as 2121231234 into one with dashes like so: 212-123-1234.
I don't know in advance how long the string of numbers will be,
it might be 12121231234, it might even be 0012121231234,
in which case I want it to turn into 1212-123-1234, and 001212-123-1234, respectively.
So far, this is what I've come up with:
$phone_number = '2121231234';
$phone_number = str_split($phone_number); // [2,1,2,1,2,3,1,2,3,4]
$phone_number = array_reverse($phone_number); // [4,3,2,1,3,2,1,2,1,2]
array_splice($phone_number, 4, 0, '-'); // [4,3,2,1,-,3,2,1,2,1,2]
array_splice($phone_number, 8, 0, '-'); // [4,3,2,1,-,3,2,1,-,2,1,2]
$phone_number = array_reverse($phone_number); // [2,1,2,-,1,2,3,-,1,2,3,4]
$phone_number = implode($phone_number); // "212-123-1234"
Which works, but seems to be far too much to accomplish such a simple task.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样
Like so
尝试使用正则表达式:
Try it with regular expressions:
尝试一下
Try it