Simple RegEx Changes to Verify Phone Number

I have this function to check my phone number:

function isValid( $what, $data ) { switch( $what ) { // validate a phone number case 'phone_number': $pattern = "/^[0-9-+]+$/"; break; default: return false; break; } return preg_match($pattern, $data) ? true : false; } 

I want to modify this regex to accept the following: characters ) ( (800) and space .

So, for example, this number will pass the test, right now it will not pass:

+1 (201) 223-3213

+4
source share
4 answers

Build a regular expression step by step. Also consider that spaces are truncated before matching.

  • at the beginning, there may or may not be a + sign. This should also be avoided. \+?
  • then one or more digits comes before the part with the parenthesis [0-9]+ You might want to write [0-9]* if the number can start directly from the group in brackets
  • then, optionally, a group of numbers appears in parentheses: (\[0-9]+\)? . Suppose that only one such group is allowed.
  • then a local phone number is dialed, hyphens are also allowed: [0-9-]*
  • the end character must be a number [0-9] , a hyphen is not allowed here

     ^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$ 

See the result here . Trimming spaces looks like $trimmed = str_replace(' ', '', $pattern); .

+7
source

How about this regex:

 /^[0-9-+()\s]+$/ 

See in action here

+3
source
 '/\(?\b[0-9]{3}\)?[-. ]?[0-9]{3,5}[-. ]?[0-9]{4,8}\b/' 
+1
source

Since you seem to be using this for verification, you can use str_replace('[\s\+\-\(\)]', '', $data) to get a string that should (if the phone number is valid) contain only numbers. You can easily verify this assumption by doing preg_match('\d{11}', $data) ( {11} means 11 digits, if the valid range, use min, max, like this {min,max} , like \d{10,11} ).

It is worth noting that this is not as thorough as Lorlin responds by ignoring any illegal use of brackets, + or - s. You might want to use a combination of two or any other that best suits your needs.

+1
source

All Articles