Why the regular season fails?

// Правильные: $correctNumbers = [ '84951234567', '+74951234567', '8-495-1-234-567', ' 8 (8122) 56-56-56', '8-911-1234567', '8 (911) 12 345 67', '8-911 12 345 67', '8 (911) - 123 - 45 - 67', '+ 7 999 123 4567', '8 ( 999 ) 1234567', '8 999 123 4567' ]; // Неправильные: $matches = []; $incorrectNumbers = [ '02', '84951234567 позвать люсю', '849512345', '849512345678', '8 (409) 123-123-123', '7900123467', '5005005001', '8888-8888-88', '84951a234567', '8495123456a', '+1 234 5678901', /* неверный код страны */ '+8 234 5678901', /* либо 8 либо +7 */ '7 234 5678901' /* нет + */ ]; $regexp = '/^((-| )?[()]?){1,}(\+7|8)((-| )?[()]?){1,}((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]$/g'; foreach($correctNumbers as $value) { echo "{$value} -\n"; if(preg_match_all($regexp, $value)) { echo $value; echo "verno\n"; } else { echo "ne verno {$value}\n"; } } 
  • It is better for each admissible format to create its own regular schedule so as not to be confused. Even if you fix yours, then no one will be able to support it later, including you. Better yet, come from the other end: for example, as I described in this answer . - neluzhin

1 answer 1

preg_match_all () and so does "\ g", so you do not need this modifier:

 $regexp = '/^((-| )?[()]?){1,}(\+7|8)((-| )?[()]?){1,}((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]((-| )?[()]?){1,}[0-9]$/';