PHP Number Cleaner RegEx

I have a function that I am using in PHP to work with numbers. The goal is to clear the number and, if necessary, convert zeros to zero. This started for me to be used in prep for sql, but is now used elsewhere. Here he is:

function clean_num ($num, $null_to_zero = true) {
  $num = preg_replace("/[^-0-9.0-9$]/","",$num);
  if (strlen($num) == 0)
    $num = ($null_to_zero) ? 0 : null;
  else if (strlen($num) == 1 && ($num == '-' || $num == '.'))
    $num = ($null_to_zero) ? 0 : null;
  return $num;
}

      

Does anyone have any ideas for a quick and better way to do this? It works, the regex is simple enough and should cover all the cases I need, but ... the diff regex can do anyway without any other garbage. Regex is not my strength. Thanks!

+2


a source to share


1 answer


The regex [^-0-9.0-9$]

matches any char that

  • no hyphen
  • not a number
  • not a .

  • not a $



there is no need to have two 0-9

in the char class, so your regex is effective: [^-0-9.$]

or[^-\d.$]

+3


a source







All Articles