从电话号码输入字段中提取号码 (PHP)

发布于 2025-01-06 16:37:48 字数 439 浏览 6 评论 0原文

我有一个电话号码输入字段,允许用户以他们想要的任何格式添加电话号码(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 技术交流群。

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

发布评论

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

评论(4

坏尐絯℡ 2025-01-13 16:37:48

使用 preg_replace 删除任何非数字:

$numbers = preg_replace('/[^\d]/','',$Phone);

注意:'[^\d]' 可以替换为 '\D'(在非 unicode 模式下安全)。

Use preg_replace to remove any non-digits:

$numbers = preg_replace('/[^\d]/','',$Phone);

Note: '[^\d]' can be replaced with '\D' (safe in non-unicode mode).

你又不是我 2025-01-13 16:37:48
$Phone = preg_replace('/[^\d]/', '', $Phone);
$Phone = preg_replace('/[^\d]/', '', $Phone);
暖心男生 2025-01-13 16:37:48

为什么不直接替换字符串中非数字的所有内容呢?

$number = preg_replace("/[^0-9]/", '', $Phone);

Why not just replace everything in the string that is not a digit?

$number = preg_replace("/[^0-9]/", '', $Phone);
攒一口袋星星 2025-01-13 16:37:48

尝试一下

if (!preg_match("/^[0-9\-]*$/",$Phone)) {
    echo "Only Numeric and strip (-)";
}

示例:

良好:0877-9320-9356

失败:0877 9320 9356087793209356

Try it

if (!preg_match("/^[0-9\-]*$/",$Phone)) {
    echo "Only Numeric and strip (-)";
}

Example:

Good: 0877-9320-9356

Failed: 0877 9320 9356 or 087793209356

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