How to check a string for an integer? Not using regulars and the ctype_digit function. There should be no letters, points, etc. in the line.
2 answers
Removed options with is_numeric () and is_int () from the answer - they do not give the desired result *
Type coercion and strict validation:
if((integer)$foo === $foo || (string)((integer)$foo) === $foo) - Not suitable. The string for the presence of an integer. Without any characters, only numbers and that's it. - Alexander Chernozhukov
- I propose instead of strpos to simply wrap the variable in trim () before checking it - dekameron
- @Denis Khvorostin, stumble on this: is_numeric ('1e10') - VenZell
|
The first thing that came to mind:
<?php $cases = array('1234567890', '1e10', '1.5'); $allowed_chars = range('0 ', '9 '); for ($i = 0; $i < count($cases); ++$i) { $is_there_bad_symbols = false; $current_case = $cases[$i]; for ($j = 0; $j < strlen($cases[$i]); ++$j) { $char = $current_case[$j]; if (!in_array($char, $allowed_chars, true)) { $is_there_bad_symbols = true; break; } } if ($is_there_bad_symbols) { echo $current_case . ' - test failed' . PHP_EOL; } else { echo $current_case . ' - test passed' . PHP_EOL; } } 1234567890 - test passed 1e10 - test failed 1.5 - test failed Or short:
<?php $allowed_chars = range('0 ', '9 '); for ($i = 0; $i < strlen($string); ++$i) { $char = $string[$i]; if (!in_array($char, $allowed_chars, true)) { $is_there_bad_symbols = true; break; } } echo $is_there_bad_symbols ? 'test failed' : 'test passed'; |
/^\d+$/is quite appropriate :) But it’s better to send incomprehensible restrictions (do not use regulars, don’t wear a blue-buttoned shirt, etc.) in the forest. - user6550