preg_match() or similar function for checking currency

后端 未结 2 1946
耶瑟儿~
耶瑟儿~ 2021-01-17 05:24
1.449,00
1.000.000,55
19,90
etc
etc

I know what I listed above are very variable but there are possibilities for currency. I\'m looking for a

相关标签:
2条回答
  • 2021-01-17 05:59

    Add + after the ] to allow more than just one character.

    0 讨论(0)
  • 2021-01-17 06:11

    Something like this should work:

    /^((?:\d{1,3}[,\.]?)+\d*)$/
    

    This matches:

    ^         - 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
    

    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.

    You can see it passes all of your tests.

    Edit: An updated regex looks like this:

    ^((?:\d\.\d{3}\.|\d{1,3}\.)?\d{1,3},\d{1,2})$
    

    Where we match either:

    • \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 ?)

    Then, we match:

    • \d{1,3}, - One to three digits and a comma, followed by
    • \d{1,2} - One or two digits
    0 讨论(0)
提交回复
热议问题