去除字符串中的非数字字符

45

我有一个保存在$phone变量中的电话号码,它长这样:(555) 555-5555。我想让它看起来像这样:5555555555。我该如何去掉字符串中的破折号、空格和括号?

4个回答

109

使用正则表达式 (regexp)。具体来说,使用preg_replace函数:

$phone = preg_replace('/\D+/', '', $phone);

26
preg_replace("/[^0-9]/", "", $phone);

完美 - 将 '(555).555-55.55' 清理为 '5555555555' - jadeallencook

3

对于不想使用正则表达式的人来说,传统的方法比较繁琐:

implode(array_filter(str_split('(555) 555-5555'), 'is_numeric'));

2

方法一

另一个选择是使用简单的表达式和 preg_match_all

[0-9]+

测试

$phone_number_inputs = ['(555) 555-5555', '(444) 444 4444', '333-333-3333', '1-222-222-2222', '1 (888) 888-8888', '1 (777) 777-7777',
    '11111(555) 555-5555'];

$phone_number_outputs = [];
foreach ($phone_number_inputs as $str) {
    preg_match_all('/[0-9]+/', $str, $numbers, PREG_SET_ORDER, 0);

    foreach ($numbers as $number) {
        $phone_number .= $number[0];
    }

    if (strlen($phone_number) == 10 || strlen($phone_number) == 11) {
        array_push($phone_number_outputs, $phone_number);
        print(" " . $phone_number . " may be a phone number! \n");
    } else {
        print(" " . $phone_number . " may not be a phone number! \n");
    }
    $phone_number = null;
}

var_export($phone_number_outputs);

输出

 5555555555 may be a phone number! 
 4444444444 may be a phone number! 
 3333333333 may be a phone number! 
 12222222222 may be a phone number! 
 18888888888 may be a phone number! 
 17777777777 may be a phone number! 
 111115555555555 may not be a phone number! 

var_export($phone_number_outputs);将会输出:

array (
  0 => '5555555555',
  1 => '4444444444',
  2 => '3333333333',
  3 => '12222222222',
  4 => '18888888888',
  5 => '17777777777',
)

方法二

最好找到类似于方法1的解决方案。

但是,根据我们可能有的输入,我们还可以设计一些更复杂的表达式,例如:

^(?:[0-9][- ])?\(?[0-9]{3}\)?[- ][0-9]{3}[- ][0-9]{4}$

如果您想简化/修改/探索表达式,可以在regex101.com的右上方面板中找到解释。如果您愿意,您还可以在此链接中查看它如何匹配一些示例输入。
RegEx Circuit是一个jex.im可视化正则表达式的工具: enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接