Reputation: 4300
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.
Upvotes: 5
Views: 2498
Reputation: 35818
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).
Upvotes: 5
Reputation: 111
Try it
if (!preg_match("/^[0-9\-]*$/",$Phone)) {
echo "Only Numeric and strip (-)";
}
Example:
Good: 0877-9320-9356
Failed: 0877 9320 9356
or 087793209356
Upvotes: 0
Reputation: 24661
Why not just replace everything in the string that is not a digit?
$number = preg_replace("/[^0-9]/", '', $Phone);
Upvotes: 2