Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers from phone number input field (PHP)

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.

like image 274
Luke Shaheen Avatar asked Feb 22 '23 10:02

Luke Shaheen


2 Answers

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).

like image 79
CanSpice Avatar answered Mar 06 '23 01:03

CanSpice


$Phone = preg_replace('/[^\d]/', '', $Phone);
like image 23
Tim Fountain Avatar answered Mar 06 '23 03:03

Tim Fountain