AKor
AKor

Reputation: 8882

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?

Upvotes: 47

Views: 39021

Answers (4)

Emma
Emma

Reputation: 27723

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("🍏 " . $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);

Output

🍏 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! 

and var_export($phone_number_outputs); would print:

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

Method 2

It would be best to find solutions similar to method 1.

However, we can also design some more complicated expressions depending on the inputs that we might have, such as with:

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

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Upvotes: 3

mario
mario

Reputation: 145482

Cumbersome method for regex avoiders:

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

Upvotes: 4

Paulraj
Paulraj

Reputation: 3397

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

Upvotes: 27

outis
outis

Reputation: 77400

With a regexp. Specifically, use the preg_replace function:

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

Upvotes: 110

Related Questions