Search code examples
phpinputdecimaluser-input

How filter decimal input in PHP and sanitize it


I want filter the user's input of a decimal value and I want allow commas and points.

I'm using the following piece of code to accomplish it:

$user_input = round(filter_input(INPUT_POST, 'test', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION|FILTER_FLAG_ALLOW_THOUSAND),2);

With the first filter all works fine if I enter decimal values with points, but if I enter a decimal value with commas the function is deleting the comma and the decimal part too. Could someone help me? Thanks


Solution

  • You can use regular expressions for this, like this one:

    preg_match_all('/^(\d+(?:[\.\,]\d{1,})?)$/', $input, $output);
    

    In the $output variable you'll get the results. If the output it's not correct you'll just get an empty array.

    To see how the preg_match_all method works go here: http://php.net/manual/es/function.preg-match-all.php

    And to know more about regexps go here: http://php.net/manual/es/reference.pcre.pattern.syntax.php