代码点火器数字正则表达式,包括点和逗号


Codeigniter numeric regex including dot and comma

我正在使用codeigniter框架。

我的验证规则是这样的

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

它适用于包含点的数字。在我的国家,我们使用点(.)和逗号(,)。我想更改点和逗号的代码点火器正则表达式。

这是代码点火器正则表达式

return (bool)preg_match( '/^['-+]?[0-9]*'.?[0-9]+$/', $str);
如果我输入带点的数字,则返回真,

但如果输入带逗号的数字,则返回假,但它应该返回真。

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

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

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