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

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