0

I am having issues making a function that validates that a phone number is in this exact format(xxx)xxx-xxxx.

My attempt was to use preg_match to confirm that the number is in the given format, but I'm having issues with the pattern.

preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)

I think my issue is that I don't know how to handle parenthesis in preg_match.

user3225440
  • 231
  • 5
  • 14
  • possible duplicate of [Simple phone number regex for php](http://stackoverflow.com/q/13111295) – mario Sep 19 '15 at 02:10

2 Answers2

2

You need to escape parenthesis : \( and \)

try this:

$n = "(123)456-3890";
$p = "/\(\d{3}\)\d{3}-\d{4}/";

preg_match($p,$n,$m);

var_dump($m);
ElefantPhace
  • 3,806
  • 3
  • 20
  • 36
  • Thanks, I got it to work using your format. I have a question though. I've seem examples with "^" at the start of the pattern and "$" at the end. What are those for? – user3225440 Sep 19 '15 at 02:24
  • Beginning and end respectively. You would use iff you're validating a single input and the phone number should be the only thing allowed. – ElefantPhace Sep 19 '15 at 02:35
1

You can have all this number validation by this code,

<?php
$array = array(
'0 000 (000) 000-0000',
'000 (000) 000-0000',
'0-000-000-000-0000',
'000 (000) 000-0000',
'000-000-000-0000',
'000-00-0-000-0000',
'0000-00-0-000-0000',
'+000-000-000-0000',
'0 (000) 000-0000',
'+0-000-000-0000',
'0-000-000-0000',
'000-000-0000',
'(000) 000-0000',
'000-0000',
'+9981824139',
9981824139,
919981824139,
'+919981824139',
'qwqwqwqwqwqwqw'
);

foreach($array AS $no){    
            var_dump( ( preg_match( '/\d?(\s?|-?|\+?|\.?)((\(\d{1,4}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)\d{3}(-|\.|\s)\d{4}/', $no )
            ||
            preg_match('/([0-9]{8,13})/', str_replace(' ', '', $no))
            ||
            ( preg_match('/^\+?\d+$/', $no) && strlen($no) >= 8 && strlen($no) <= 13 ) )
          );
    }

//var_dump (preg_match('/([0-9]{8,12})/', '99818241') );
//var_dump( strlen(9981) );

//var_dump (preg_match('/^\+?\d+$/', '+12345678') );
//var_dump (preg_match('/^\+?\d+$/', '12345678') );

This will Validate your all type of phone number and output would be

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
manish1706
  • 1,571
  • 24
  • 22