开发者

Stripping a string of its non-numeric characters

I have a phone number开发者_运维技巧 stored in $phone, it looks like this: (555) 555-5555. I want it to look like this: 5555555555. How do I take the string and strip it of hyphens, spaces, and parenthesis?


With a regexp. Specifically, use the preg_replace function:

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


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


Cumbersome method for regex avoiders:

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


Method 1

Another option is to simply use the preg_match_all with a simple expression:

[0-9]+

Test

$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("
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜