Search code examples
phpregexfilter-var

PHP filter_var() function allowing more than one minus in integer numbers


I am trying to filter integers using filter_var(), but in this case:

echo filter_var('-3-6-5', FILTER_SANITIZE_NUMBER_INT); // Output: -3-6-5

Instead of -3-6-5 i expect to get -365.

Someone know how to solve this or a regex that do this?

Thanks for any help!


Solution

  • echo preg_replace('~^[^-\d]|(?<!^)\D~', '', '-3-6-5'); // -365
    

    It will remove anything that is not a digit, keeping - sign in the beginning of the string