PHP phone number validation – revisited

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.

/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i

This single function detects for all the patterns in the original post and more.

Example

$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' ) . '<br/>';
}

Output

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