Help to create a regular expression that checks the string so that it contains only numbers (from 7 to 15), but also among the digits there could be the characters "-", "(", ")", "" (space). Moreover, the spaces and symbols "-" were not more than 5, and each of the brackets is not more than 1. For example 053654895665, or 96 (8) 956-17-26

  • Phone validation is the bottom, as in America and other countries there may be phone numbers with letters, this is comparable to the validation of the name and surname, I don’t understand why customers think that a person is not able to write his full name - this is Naumov

2 answers 2

For example 053654895665, or 96 (8) 956-17-26

For your example, this option is suitable:

$str = 'Например 053654895665, или 96(8) 956-17-26'; preg_match_all('~\b(?:\d{7,15}|\d{2}\(\d\)\s?\d{3}(?:-\d{2}){2})\b~', $str, $arr); var_dump($arr); 

UPD: Option with the list of numbers:

 $str = '+375296398545 +375(29)6398545 375296398545 375-29-639-85-45 +375-29-639-85-45 +375(29)639-85-45 375(29)639-85-45 375(29)639 85 45 +375 29 639 85 45 375 29 6398545'; $patt = '~ \b \+? (?: # +375296398545 или 375296398545 \d{7,15} | # +375(29)6398545 \d{3} \( \d{2} \) \d{7} | # 375-29-639-85-45 (?: \d{3}- \d{2}- ){2} \d{2} | # +375(29)639-85-45 и все остальные \d{3} [\h(] \d{2} [\h)] \d{3} (?: [\h-]? \d{2} ){2} )\b ~x'; preg_match_all($patt, $str, $arr); print_r($arr); 

Result (all numbers from the list) :

 Array ( [0] => Array ( [0] => 375296398545 [1] => 375(29)6398545 [2] => 375296398545 [3] => 375-29-639-85-45 [4] => 375-29-639-85-45 [5] => 375(29)639-85-45 [6] => 375(29)639-85-45 [7] => 375(29)639 85 45 [8] => 375 29 639 85 45 [9] => 375 29 6398545 ) ) 

PS: Do not foresee everything.

    Validation of the phone is the bottom, as in America and other countries there may be phones with letters, this is comparable to the validation of the name and surname. I do not understand why customers think that a person is not able to write his full name, this is absurd.

    Well, as an algorithm, I can offer the following:

     // удалим разрешенные символы из строки $phoneCheck = str_replace(['+', ' ', ')', '(', '-'], '', $phone); // далее приводим к integer $phoneCheckSumm = (int) $phoneCheck; // сравниваем две переменные if($phoneCheck == $phoneCheckSumm && $phoneCheck >= 7 && $phoneCheck <= 15) { echo 'все верно'; } else { echo 'что то не так'; } 

    The logic is simple, if, when holding an integer, php cuts off letters or symbols, then the variables will not be equal. In general, it is better not to validate such things, because it will create more inconvenience than user benefits.

    ps 15 is not a number, but a number, so the task is incorrect.