tags:

views:

51

answers:

1

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 diff regex might do all the same without other junk. Regex is not my strength. Thanks!

+2  A: 

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.$]

codaddict
Removing the $ from the regex gave me the exact results I wanted. Just numbers, don't lose any precision, don't lose negatives, strip any alpha, etc. Thanks!
Erick