View Full Version : pregmatch script for phone number
pkrishna42
10-05-2017, 07:12 AM
I want to validate phone number with preg_match in this below format
1 222 123 1234
1 333 123 1234
1231231234
1-123-123-1234
1123-123-1234
123-123-1234
My code
preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)
jscheuer1
10-05-2017, 03:13 PM
I think that may be too many possibilities to cover in one preg_match test. However, assuming it would be OK if the field contained more spaces or dashes than expected, or a mixture of spaces and dashes, and perhaps not as expected, one could go with:
preg_match("/^[0-9]{10,11}$/", preg_replace("/ |-/", '', $field))
You could test the string for its overall length first in order to make sure there weren't a lot of extra delimiters in there. You could use the strlen() function. It would have to return between 10 and 14 before stripping out the delimiters to have even a chance of fitting your template. That would narrow it down. Otherwise I think, if you wanted to be really precise in following your template, you would have to make a number of preg_match tests in a row, one for each of the possible configurations, with of course some combining where possible), and if the field passed any of those, it would be accepted.
On second thought, this would be pretty good, but still accept some things you haven't precisely listed in your template strings:
preg_match("/^\d?[- ]?\d{3}[- ]?\d{3}[- ]?\d{4}$/", $field)
BTW \d is the same as [0-9] and ? is the same as {0,1}
jscheuer1
10-05-2017, 05:58 PM
This would be even better. I'm no longer sure that anything not fitting your template strings would pass this (but something might):
$delimiter = strpos($field, " ") === 1? " " : "-";
preg_match("/^\d?" . $delimiter . "?\d{3}" . $delimiter . "?\d{3}" . $delimiter . "?\d{4}$/", $field);
Deadweight
10-05-2017, 06:03 PM
This is similar to jscheuer expression
^(\+1|001)?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([ .-]?)([0-9]{4})
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.