-1

I would like to allow numbers and the following characters: -, +, (, )

$phone = '1(54)+45-21';
var_dump(preg_match('/^[\(\)0-9+-]+$/', $phone));

Well, that works great. But I would also like to allow spaces between each character. So the value of $phone could be like +45 (548) - 541 55 11 but it would also be valid without any spaces.

How can I allow optional spaces?

Reza Saadati
  • 1,224
  • 13
  • 27

1 Answers1

1

Trying to predict all the nonsensical ways people can pick to write a phone number will do nothing but erode your sanity.

$phone = '+1 (234) 567-8900';

// 1. Delete all non-consequential characters.
$phone_bare = preg_replace('/[^\d+]/', '', $phone);

// 2. Check against a simple, sane format.
//      eg: optional +, 11 digits
$result = preg_match('/^\+?\d{11}$/', $phone_bare);

var_dump($phone, $phone_bare, $result);

Output:

string(17) "+1 (234) 567-8900"
string(12) "+12345678900"
int(1)
Sammitch
  • 30,782
  • 7
  • 50
  • 77