Reputation: 12740
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 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.'; }
Upvotes: 0
Views: 3550
Reputation: 59709
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?
)Then, we match:
\d{1,3},
- One to three digits and a comma, followed by\d{1,2}
- One or two digitsUpvotes: 5
Reputation: 324790
Add +
after the ]
to allow more than just one character.
Upvotes: 0