从电话号码输入字段中提取号码 (PHP)
我有一个电话号码输入字段,允许用户以他们想要的任何格式添加电话号码(555-555-5555、(555) 555 - 5555 等)。
由于它只是一个电话号码字段,因此我可以忽略除字段中的数字之外的所有内容。
我目前正在使用以下代码。 它提取所有数字,但问题是它们不按顺序排列 - 顺序混乱。
如何按照数字在原始字符串中出现的顺序提取数字?
preg_match_all('/\d+/', $Phone, $matches);
$Phone = implode('', $matches[0]);
编辑:它们实际上并不是这个函数的混乱顺序 - 我将数字插入到 int(10) 数据库字段中,这导致了混乱。但是,下面的答案仍然是实现我的目标的更有效的方法。
I've got a phone number input field, which allows a user to add a phone number in whatever format they want (555-555-5555, (555) 555 - 5555, etc).
Since it a phone number field only, I can ignore everything but the numbers in the field.
I'm currently using the following code. It extracts all the numbers, but the issue is that they are not in order - it's in a jumbled order.
How do I extract the numbers in the order that they appear in the original string?
preg_match_all('/\d+/', $Phone, $matches);
$Phone = implode('', $matches[0]);
Edit: They are actually not in a jumbled order from this function - I was inserting the numbers into a int(10) database field, which caused the jumbling. But, the answers below are still a more efficient way of accomplishing my goal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
preg_replace
删除任何非数字:注意:'[^\d]' 可以替换为 '\D'(在非 unicode 模式下安全)。
Use
preg_replace
to remove any non-digits:Note: '[^\d]' can be replaced with '\D' (safe in non-unicode mode).
为什么不直接替换字符串中非数字的所有内容呢?
Why not just replace everything in the string that is not a digit?
尝试一下
示例:
良好:
0877-9320-9356
失败:
0877 9320 9356
或087793209356
Try it
Example:
Good:
0877-9320-9356
Failed:
0877 9320 9356
or087793209356