PHP regular expression to match price or quantity

I need a regular expression that will match the price or amount.

He must match these

  • 100
  • 410.00
  • 0.12

but not these

  • 100,000
  • -600.00
  • +0.12
  • 0.1234

This works for all of the above cases except for single values ​​like 1

/^[0-9]*\.?[0-9]{2}+$/

How can I configure it to match integers? And can anyone explain why the current one is wrong?

+3
source share
5 answers

I suggest a small correction to Tom Revell's regex, as you can still enter a few 0 as the first digits. those. 00002.23, which is most likely incorrect.

/^([1-9][0-9]*|0)(\.[0-9]{2})?$/
+7
source

:

/^[0-9]+(\.[0-9]{2})?$/
+4

, , :

, 0 , ​​ , , 0 1 , ​​ 2

, - .

:

/^ [0-9] + (\. [0-9] {2})? $/

1 , , 2 .

+2

, .

, int , , . , , , . , - 12.34512 .1, .

//untested

$amount = "$0.12"
if( $amount && $amount[0] == '$' ) {
    ltrim($amount, '$');
}
$int_amount = (int) $amount;
$int_amount = round($int_amount, 2);
if( $amount <= 0 ) {
    //error
}

, (, , regexp ), , , , " ", 12 .

+1

The best way to work out a regular expression is to start by letting the idea slip on paper. Try to draw your regular expression or write it in some pseudo-code, check it in your head and make sure that it is right before you get stuck in the regex syntax.

0
source

Source: https://habr.com/ru/post/1760428/


All Articles