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.
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).
$Phone = preg_replace('/[^\d]/', '', $Phone);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With