Search code examples
phpregexnumericsanitization

Sanitize a number which may include dollar symbols, hyphens and dots


I have a function I use in PHP to work with numbers. The intent is to clean the number and, optionally, convert nulls to zero. It began for me for use in prep for sql, but is now used in more places. Here it 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 on a faster, better way of doing this? It works, the regex is simple enough and should cover all cases I need, but... A different regex might do all the same without other junk.


Solution

  • The regex [^-0-9.0-9$] matches any char that is

    • not a hyphen
    • not a digit
    • not a .
    • not a $

    there is no need to have two 0-9 in the char class, so effectively your regex is: [^-0-9.$] or [^-\d.$]