From PHP sanitize filters list there is one option to sanitize integers:
FILTER_SANITIZE_NUMBER_INT - Remove all characters except digits, plus and minus sign.
If we use:
filter_var($var2San, FILTER_SANITIZE_NUMBER_INT);
This will clean dots .
and commas ,
but the +
and -
signs remain. E.g.: ++++ --- 1.110,4 <b>m<sup>2</sup></b>
is sanitized to ++++---111042
. Ideally the filter_var
would return false
when the number was 0, i.e. the number would have to be a natural number, more specifically, a positive integer.
Therefore a FILTER_SANITIZE_NUMBER_NATURAL
would be handy... Is there a workaround for this or do I need a RegExp?
Using regexp functions seems overkill, since there is another way to use the filter_var
function:
filter_var($var2San, FILTER_VALIDATE_INT,
array('options' => array('min_range' => 1)));
The FILTER_VALIDATE_INT is listed under the PHP filters flags and without defining a specific flag (in the $options
array), the filter_var
will detect and return the number if it is valid, returning FALSE
otherwise. Examples:
-1
→ FALSE
0
→ FALSE
1
→ 1
+ 1
→ FALSE
+2
→ 2
++3
→ FALSE
4+
→ FALSE
5.6
→ FALSE
7,8
→ FALSE
This guarantees that the number you test is a natural number (a positive integer without any other characters besides digits around it, except a +
at the left). Even if it has a +
ahead of it, it will only return the number itself.
There is a small setback though, if the number is over 2147483647, it will also return FALSE
(maximum positive value for a 32-bit signed binary integer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With