fork download
  1. <?php
  2.  
  3. $correctNumbers = [
  4. '84951234567', '+74951234567', '8-495-1-234-567',
  5. ' 8 (8122) 56-56-56', '8-911-1234567', '8 (911) 12 345 67',
  6. '8-911 12 345 67', '8 (911) - 123 - 45 - 67', '+ 7 999 123 4567',
  7. '8 ( 999 ) 1234567', '8 999 123 4567'
  8. ];
  9.  
  10. $incorrectNumbers = [
  11. '02', '84951234567 позвать люсю', '849512345', '849512345678',
  12. '8 (409) 123-123-123', '7900123467', '5005005001', '8888-8888-88',
  13. '84951a234567', '8495123456a',
  14. '+1 234 5678901', /* неверный код страны */
  15. '+8 234 5678901', /* либо 8 либо +7 */
  16. '7 234 5678901' /* нет + */
  17. ];
  18.  
  19. $regex = '/^ *(\\+ *7|8)([-() ]*[0-9]){10}$/'; //написанная регулярка
  20.  
  21. function checkNumbers($numbers, $regex)
  22. {
  23. foreach ($numbers as $number)
  24. {
  25. echo "$number - ";
  26. echo (preg_match($regex, $number) ? "ok" : "failed");
  27. echo "\n";
  28. }
  29. }
  30.  
  31. echo "These should be ok:\n";
  32.  
  33. checkNumbers($correctNumbers, $regex);
  34.  
  35. echo "\nThese should be failed:\n";
  36.  
  37. checkNumbers($incorrectNumbers, $regex);
  38.  
  39.  
Success #stdin #stdout 0.04s 52480KB
stdin
Standard input is empty
stdout
These should be ok:
84951234567 - ok
+74951234567 - ok
8-495-1-234-567 - ok
 8 (8122) 56-56-56 - ok
8-911-1234567 - ok
8 (911) 12 345 67 - ok
8-911 12 345 67 - ok
8 (911) - 123 - 45 - 67 - ok
+ 7 999 123 4567 - ok
8 ( 999 ) 1234567 - ok
8 999 123 4567 - ok

These should be failed:
02 - failed
84951234567 позвать люсю - failed
849512345 - failed
849512345678 - failed
8 (409) 123-123-123 - failed
7900123467 - failed
5005005001 - failed
8888-8888-88 - failed
84951a234567 - failed
8495123456a - failed
+1 234 5678901 - failed
+8 234 5678901 - failed
7 234 5678901 - failed