8

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?

Armfoot
  • 4,663
  • 5
  • 45
  • 60

1 Answers1

17

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:

  • -1FALSE
  • 0FALSE
  • 11
  • + 1FALSE
  • +22
  • ++3FALSE
  • 4+FALSE
  • 5.6FALSE
  • 7,8FALSE

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).

Armfoot
  • 4,663
  • 5
  • 45
  • 60
  • 2
    There's also `ctype_digit()`, which doesn't not have a limitation on its maximum value, but also does not allow "+", thousands separators, a decimal place, etc. It is literally as if you had used the regex "^[0-9]+$" to validate your string, though obviously much faster. – Ghedipunk Jul 20 '15 at 16:37
  • 2
    @Ghedipunk Despite only returning `false` or `true` [ctype_digit](http://php.net/manual/en/function.ctype-digit.php) seems a very good alternative, appreciated! – Armfoot Jul 20 '15 at 16:49
  • 1
    Very clean. Love it. – levi Feb 18 '17 at 02:19