Through example learning regular expressions (2) - check the "money" input

xiaoxiao2021-03-06  64

Check a string that represents money

OK, now we can do some useful things with what we just learned: use a regular expression to check if the "money" is correct. There are four money representations. We can accept: "10000.00" and "" 10,000 "," 10000 "and" 10,000 "without" division ". Let's start: ^ [1-9] [0-9] * $ This means that any one does not start with 0, but this also means Holding a character "0" does not pass, so we use the following form: ^ (0 | [1-9] [0-9] *) $ 0 or a number that does not start with 0. We can also allow beginning A negative number: ^ (0 | -? [1-9] [0-9] *) $ This means that a 0 or one may be a number of numbers not 0. OK, let us not be so strict. Let The user started with 0. The matching of the negative is also removed, because the money can't be negative. Below we want to add a possible fractional part: ^ [0-9] (. [0-9] )? $ Must be explained, there should be at least 1 digit after the decimal point, so "10." is not passed, but "10" and "10.2" are passed. ^ [0-9] (. [. 0-9] {2})? $ So we must have two behind, if you think it is too harsh, you can: ^ [0-9] (. [0-9] {1,2}) • This allows the user to write only a decimal. Below we should consider the comma in the figures, we can: ^ [0-9] {1,3} (, [0-9] {3}) * ( [0-9] {1,2})? $ "1 to 3 numbers, followed by any comma 3 numbers" very simple, isn't it? But let us make a comma becomes an option, not a must: ^ ([0-9] | [0-9] {1,3} (, [0-9] {3}) *) (. [0-9] {1, 2})? $ This is the final As a result, don't forget " " to use "*" to replace if you feel that the empty string can be accepted (strange, why?) Finally, don't forget to drop the backslash, general mistakes when using a function All here. OK, when your verification is complete, use str_replace (",", ", $ money) to set your comma, then set it to Double so that we can use it. Transfer from: http://se2k.51.net/myphp/

转载请注明原文地址:https://www.9cbs.com/read-119625.html

New Post(0)