"1-----1-+-1" is a valid integer value in PHP?

Asked

Viewed 159 times

9

I’m testing a PHP value filter function called filter_var(). And a of your filters, focused on values like int seems to accept any combination of numbers, + and -. Example:

filter_var("1teste2", FILTER_SANITIZE_NUMBER_INT) // 12
filter_var("1-teste-2", FILTER_SANITIZE_NUMBER_INT) // 1--2
filter_var("1--1--+--1", FILTER_SANITIZE_NUMBER_INT) // 1--1--+--1

Is this a normal behavior? The language accepts this type of value as int without problems, or is a bug of the filter function?

2 answers

10

According to the documentation, this behavior is expected. In the case FILTER_SANITIZE_NUMBER_INT:

Remove all characters except digits, plus and Minus Sign.

Removes all characters except digits([0-9]), addition(+) and subtraction signals(-).

10


According to the documentation, yes. You know, it’s PHP, things are made to work more or less. And the function does what promises even if the expectation of the programmer is another:

Remove all characters except digits, plus and Minus Sign.

The function with this flag does not promise to transform the string in a valid integer, it promises to only remove all other characters other than digits and less and more.

Then the title question must be answered with a no. But the function used does not have the task to solve this. The name of the flag makes you understand something she doesn’t do.

Have examples of flag]2 that probably suits you better. See working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation.

  • $var = preg_replace_all('~[^\d+-]~', '', $var);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.