preg_match() 或用于检查货币的类似函数 [英] preg_match() or similar function for checking currency
问题描述
1.449,00
1.000.000,55
19,90
etc
etc
我知道我上面列出的东西变化很大,但货币是有可能的.我正在寻找 preg_match()
示例或任何其他函数来处理上述可能的情况.我尝试了下面的示例,但它无法正常工作.有没有机会给我一个最合适的模式?
I know what I listed above are very variable but there are possibilities for currency. I'm looking for a preg_match()
example or any other function to deal with possible cases above. I tried with example below but it is not working properly. Any chance given me a most appropriate pattern for it?
if (! preg_match('/^[0-9.,]$/', $currency)) { echo 'No good.'; }
推荐答案
这样的事情应该可行:
/^((?:\d{1,3}[,\.]?)+\d*)$/
这匹配:
^ - 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
它的工作原理是将所有内容迭代地匹配到分隔符的左侧(如果存在),然后使用 \d*
来选择货币的任何可选部分.
It works by iteratively matching everything to the left side of the separator (if it's present), and then has \d*
to pick up any optional fractions of currency.
您可以看到它通过了您的所有测试.
更新后的正则表达式如下所示:
An updated regex looks like this:
^((?:\d\.\d{3}\.|\d{1,3}\.)?\d{1,3},\d{1,2})$
我们匹配的地方:
\d\.\d{3}\.
- 一个数字、一个句点、三个数字、一个句点或\d{1,3}\.
- 一个和三个数字,一个句点- 以上都不是(因为
?
)
\d\.\d{3}\.
- One digit, a period, three digits, a period, OR\d{1,3}\.
- One and three digits, a period- None of the above (because of the
?
)
然后,我们匹配:
\d{1,3},
- 一到三个数字和一个逗号,后跟\d{1,2}
- 一位或两位数字
\d{1,3},
- One to three digits and a comma, followed by\d{1,2}
- One or two digits
这篇关于preg_match() 或用于检查货币的类似函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!