PHP regex - valid float number

后端 未结 7 1157
生来不讨喜
生来不讨喜 2020-11-29 09:04

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 , t

相关标签:
7条回答
  • 2020-11-29 09:47

    Regular Expressions are for matching string patterns. If you are not explicitly after validating the input string's format (but the actual value), you can also use

    filter_var("1.33", FILTER_VALIDATE_FLOAT);
    

    to make sure the input can be used as a float value. This will return FALSE if it is not a float and the float or integer value otherwise. Any type juggling rules apply.

    0 讨论(0)
  • 2020-11-29 09:49

    this is what you're looking for

    $re = "~        #delimiter
        ^           # start of input
        -?          # minus, optional
        [0-9]+      # at least one digit
        (           # begin group
            \.      # a dot
            [0-9]+  # at least one digit
        )           # end of group
        ?           # group is optional
        $           # end of input
    ~xD";
    

    this only accepts "123" or "123.456", not ".123" or "14e+15". If you need these forms as well, try is_numeric

    0 讨论(0)
  • 2020-11-29 09:49

    Why not just use is_numeric if you're not experienced with regular expressions.

    As to your regex: . matches all characters, \. matches a dot. {1} is not necessary. And I have no clue what you're trying to do with [^ ... ]. Read the regular expressions tutorial if you really want to use regular expressions somewhere in your code.

    0 讨论(0)
  • 2020-11-29 09:52

    Why not use http://php.net/manual/en/function.is-float.php ? But anyhow, the RegEx would be ^[\d]+(|\.[\d]+)$ have fun!

    0 讨论(0)
  • 2020-11-29 09:56

    You can use is_numeric() with the caveat that it accepts a bit more than one usually wants (e.g. 1e4).

    0 讨论(0)
  • 2020-11-29 10:02

    This regex:

    \d*(?:\.\d+)?
    

    will give results:

    123 -> true
    123.345 -> true
    123. -> true
    .345 -> true
    0.3345 -> true
    

    However, you must check emptiness of the input before using it because the regex also permit zero-length input.

    0 讨论(0)
提交回复
热议问题