How to mathematically check user input: does the number match one of a given sequence: 1, 10, 100, ..., 10,000,000 in PHP. Check with preg_match () is not a problem, but somehow it is not correct to check the numbers with the function intended to check strings.

if (!preg_match('/^10{0,7}$/', $_GET['insert_number'])) { echo 'число должно быть 1, 10, 100, 1000 и т.д.'; } 

How to call a sequence of numbers 1, 10, ... so that the error message is more informative?

  • one
    "the number must be a nonnegative integer power of ten" (it turned out even worse). You can check through the logarithm, looking at how close it is to an integer, or by analyzing the residuals from the division by 10 completely. - etki
  • one
    “Somehow not right” - somehow not right. The solution must pass a set of tests, be quick and undemanding of resources. In addition, user input is just a string. - Sergiks
  • Checking preg_match will be faster and easier to count different logarithms - alff0x1f
  • one
    "It will not go through / ^ 10 {0.7} $ /" 1 "" - passes successfully, checked. - Miron
  • You are right, wrote to coffee) - Sergiks

5 answers 5

Only 8 options, why not scorch? =)

 in_array($userInput, [1,10,100,1000,10000,100000,1000000,10000000]); 

Another strange option: look at valid numbers as binary - because there are only ones and zeros allowed, no longer than a byte (8 positions).

 function is10x($userInput) { $input = trim($userInput); // убрать пробелы по краям и считать строкой $binStr = sprintf('%b', intval($input,2)); // перевести в двоичное число и в строку единиц и нулей if( $binStr !== $input) return FALSE; // должно пережить двойной перевод без потерь return array_sum(str_split($binStr)) === 1; // должно содержать только одну 1 } 

Tests

Message: "The number must begin with one and, except it, can contain only zeros"

  • That's just not necessary hardcore :) - Miron
  • @Miron justify - Sergiks
  • In the version with preg_match and so hardcore, but changing the range is easier there - Miron
  • The regular expression engine may require a much larger number of operations than a search in an array of 8 elements, isn’t it? - Sergiks
  • Following your logic, the code of a php script needs to be written without translating strings and spaces - it will consume less resources, but this is not convenient, but saving "on matches"? :) This is me to the fact that both my and your options have the right to life, only your option to edit longer, in case of a change in the condition. - Miron

You can check through the logarithm, but it must be borne in mind that the functions log() and log10() always return a number of type float . You can use this hack:

 $y = 10; $x = pow((string)log10($y),1); 

the result of the work of log10() distilled into a string and fed to the pow() function, which returns an int or float depending on the result obtained

 if (is_float($x) || $y < 1) echo "Число не удовлетворяет условию"; var_dump($x); 

    Posted in Java, because I don’t use PHP

     //Проверка на то, является ли число одной из степеней 10: public boolean is10(int n) { if(n==1) return true; else if(n<1) return false; return n%10==0 && is10(n/10); } 

    Well, I tried to convert to PHP:

     function is10($n): boolean { if ($n == 1) { return true; } elseif ($n < 1) { return false; } return $n % 10 == 0 && is10($n / 10); } 

      Is it possible to make a simple cycle? since the maximum number is 10,000,000

       // Функция проверки цисла function proveritChislo($number){ // Если число больше 1 можно работать while ( $number > 1 ) { // Если не заканчивается на 0, значит не правильно $ostatok = $number % 10; if ($ostatok != 0) { return FALSE; } // убираем последний 0 $number = ($number - $ostatok) / 10; } return $number == 1; } 
      • one
        You can: in_array($number, [1,10,100,1000,10000,100000,1000000,10000000]); - Sergiks
      • @Sergiks agree, so quickly. Since computers are used not only for calculations but also for data storage !! - Saidolim
       $test="1".str_repeat("0",strlen($input)-1); if($test % $unput != 0) echo "Ошибка бла-бла-бла";