开发者

PHP Number Cleaner RegEx

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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜