Check a string indicating money
OK. Now we can use what we just learned to do something useful: Use a regular expression to check whether the input "money" is in the correct format. there are four forms of money that we can accept: "10000.00" and "10,000.00", and "10000" and "10,000" without "points ". let's start:
^ [1-9] [0-9] * $
This indicates any number not starting with 0, but it also means that the character "0" does not pass, so we use the following form:
^ (0 | [1-9] [0-9] *) $
A 0 or a number not starting with 0. We can also start with a negative number:
^ (0 | -? [1-9] [0-9] *) $
This indicates a zero or a number that may start with a negative value not 0. OK, so we should not be so strict. let the user start with 0. remove the matching of the negative number, because money cannot always be negative. what we want to add below is the possible decimal part:
^ [0-9] + (. [0-9] + )? $
It must be noted that there should be at least one digit after the decimal point. Therefore, "10." is not passed, but "10" and "10.2" are passed.
^ [0-9] + (. [0-9] {2 })? $
In this case, there must be two digits after the decimal point. If you think it is too harsh, you can do this:
^ [0-9] + (. [0-9] {1, 2 })? $
In this way, you can write only one decimal number. We should consider the comma in the number. We can do this:
^ [0-9] {1, 3} (, [0-9] {3}) * (. [0-9] {1, 2 })? $
"1 to 3 numbers followed by any comma + 3 numbers" is simple, isn't it? But let's make the comma optional, rather than necessary:
^ ([0-9] + | [0-9] {1, 3} (, [0-9] {3 })*)(. [0-9] {1, 2 })? $
This is the final result. Don't forget that "+" can be replaced with "*". If you think empty strings are acceptable, (strange, why ?) Finally, do not forget to remove the backslash when using the function. The general errors are here. OK. After your verification is complete, use str_replace (",", "", $ money) to remove the comma and set its type to double, in this way, we can use it for computing.
From: http://se2k.51.net/myphp/