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)
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)
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:
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.PHP Code:preg_match("/^[0-9]{10,11}$/", preg_replace("/ |-/", '', $field))
On second thought, this would be pretty good, but still accept some things you haven't precisely listed in your template strings:
BTW \d is the same as [0-9] and ? is the same as {0,1}PHP Code:preg_match("/^\d?[- ]?\d{3}[- ]?\d{3}[- ]?\d{4}$/", $field)
Last edited by jscheuer1; 10-05-2017 at 03:41 PM. Reason: add info
- John________________________
Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate
This would be even better. I'm no longer sure that anything not fitting your template strings would pass this (but something might):
PHP Code:$delimiter = strpos($field, " ") === 1? " " : "-";
preg_match("/^\d?" . $delimiter . "?\d{3}" . $delimiter . "?\d{3}" . $delimiter . "?\d{4}$/", $field);
- John________________________
Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate
pkrishna42 (10-10-2017)
This is similar to jscheuer expression
Code:^(\+1|001)?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([ .-]?)([0-9]{4})
-DW [Deadweight]
Resolving your thread: First Post: => EDIT => Lower right: => GO ADVANCED => Top Advance Editor drop down: => PREFIX:Resolved
pkrishna42 (10-10-2017)
Bookmarks