Codeigniter 数字正则表达式,包括点和逗号

Codeigniter numeric regex including dot and comma

我正在使用 codeigniter 框架。

我的验证规则就是这样

array(
    'field' => 'amount_per_unit'
    'label' => __('Cost'),
    'rules' => 'trim|numeric|required|greater_than[0]'
)

它适用于包含点的数字。在我的国家/地区,我们使用点 (.) 和逗号 (,)。我想为点和逗号更改 ​​codeigniter 正则表达式。

这是 codeigniter 正则表达式

return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);

如果我输入带点的数字 return 为真,但如果输入带逗号的数字 return 为假但它应该 return 为真。

如何更改包含点和逗号的正则表达式?

您可以使用字符 class 来包含这两个字符。我会这样写:

return (bool) preg_match('/^[-+]?\d+(?:[,.]\d+)*$/', $str);

正则表达式:

^          # the beginning of the string
[-+]?      # any character of: '-', '+' (optional)
\d+        # digits (0-9) (1 or more times)
(?:        # group, but do not capture (0 or more times):
  [,.]     #   any character of: ',', '.'
  \d+      #   digits (0-9) (1 or more times)
)?         # end of grouping
$          # before an optional \n, and the end of the string