Several months ago, when I was first getting familiar with regular expression, I made a post talking about PHP form validation for phone numbers and email addresses.
A couple of days ago, I revisited that post and realized how inefficient my function actually was. The entire point of regex is to recognize multiple patterns within 1 statement. Here is my revised regular expression.
{code type=php}
/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i
{/code}
This single function detects for all the patterns in the original post and more.
Example
{code type=php}
$phone_numbers = array(
‘555-555-5555’,
‘5555425555’,
‘555 555 5555’,
‘1(519) 555-4444’,
‘1 (519) 555-4422’,
‘1-555-555-5555’,
‘1-(555)-555-25555’,
);
$regex = “/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i”;
foreach( $phone_numbers as $number ) {
echo $number . ‘: ‘ . ( preg_match( $regex, $number ) ? ‘valid’ : ‘invalid’ ) . ‘
‘;
}{/code}
Output
{code type=php}
555-555-5555: valid
5555425555: valid
555 555 5555: valid
1(519) 555-4444: valid
1 (519) 555-4422: valid
1-555-555-5555: valid
1-(555)-555-5555: valid
1-(555)-555-25555: invalid
{/code}
This really helped me! I’m not really too great with PHP yet and this validation works perfectly. Thank you!
Complex regular expressions are often hard to read and therefor can be a pain to write and debug.
It is always useful to seek for proven regex before even thinking about writing one.
Thank you
Does it work for non-USA numbers though?
+55-32-1233-4567
would that read as “valid” or “invalid” with your code?
Hi Steven,
This particular regex wouldn’t work for non-North American Numbers. This regex expression would work for the number you have above.
Note, this would ONLY work for the format you provided, as well as the following alternatives:
+55-32-1233-4567
55-32-1233-4567
55 32 1233 4567
553212334567
The + is optional, the dashes can be spaces or nothing. Hope this helps!