Search code examples
phpnumber-formatting

PHP validate a number with comma and space


I want to validate a number with comma and spaces. I'm doing that by replacing comma with dot, and removing space and then using is_numeric function.

$num = "12 345,67";
$num = str_replace(',', '.', $num);
$num = str_replace(' ', '', $num);

var_dump(is_numeric($num));  //true

The above code does the job, however I'm wondering if there is any better (shorter) way to do it, maybe by making use of is_numeric function?


Solution

  • You can try this. It will allow all numeric values and decimal points.

    if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $num) == ""){
      //Validated do your thing here.
    }