PHP regex - valid float number

Viewed 30334

I want user only input 0-9 and only once "."

 patt = /[^0-9(.{1})]/

 1.2222 -> true
 1.2.2  -> false (only once '.')

help me , thank !

8 Answers

I wrote the following regex that seems to work best for my test inputs so far,

/^-?(\d|[1-9]+\d*|\.\d+|0\.\d+|[1-9]+\d*\.\d+)$/

It matches integer using the first two alternatives

\d|[1-9]+\d*

Then it look for numbers like .5, .55, .05 etc., that is beginning with a .

\.\d+

Then it looks for the same as previous but a 0 before the .

0\.\d+

Then finally it looks for patterns integer and decimal parts, such as 5.5, 5.05 etc.

[1-9]+\d*\.\d+

You can test the regex in this link

Validate float - regex101

Related