Ben*_*der 0 php regex syntax preg-match
1.449,00
1.000.000,55
19,90
etc
etc
Run Code Online (Sandbox Code Playgroud)
我知道我上面列出的内容非常多变,但有货币的可能性.我正在寻找一个preg_match()例子或任何其他函数来处理上面可能的情况.我试过下面的例子,但它不能正常工作.有机会给我一个最合适的模式吗?
if (! preg_match('/^[0-9.,]$/', $currency)) { echo 'No good.'; }
Run Code Online (Sandbox Code Playgroud)
这样的事情应该有效:
/^((?:\d{1,3}[,\.]?)+\d*)$/
Run Code Online (Sandbox Code Playgroud)
匹配:
^ - Start of string
( - Capture the following:
(?:
\d{1,3} - One to three digits
[,\.]? - And an optional separator (comma or period)
)+ - One or more times
\d* - Zero or more digits
)
$ - End of string
Run Code Online (Sandbox Code Playgroud)
它通过迭代匹配分隔符左侧的所有内容(如果它存在),然后必须\d*拾取任何可选的货币分数.
您可以看到它通过了所有测试.
编辑:更新的正则表达式如下所示:
^((?:\d\.\d{3}\.|\d{1,3}\.)?\d{1,3},\d{1,2})$
Run Code Online (Sandbox Code Playgroud)
在哪里匹配:
\d\.\d{3}\. - 一位数,一个句点,三位数,一个句号,或\d{1,3}\. - 一个和三个数字,一个句号?)然后,我们匹配:
\d{1,3}, - 一到三位数字和一个逗号,然后是\d{1,2} - 一个或两个数字