php - regex - how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01)?

后端 未结 6 2045
清酒与你
清酒与你 2020-12-05 21:26

how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01) ? I have a regex but doesn\'t seem to play well with commas

preg_match(\'/([0-         


        
6条回答
  •  醉梦人生
    2020-12-05 21:58

    Add the comma to the range that can be in front of the dot:

    /([0-9,]+\.[0-9]+)/
    #     ^ Comma
    

    And this regex:

    /((?:\d,?)+\d\.[0-9]*)/
    

    Will only match

    1,067120.01
    121,34,120.01
    

    But not

    ,,,.01
    ,,1,.01
    12,,,.01
    
    # /(
    #   (?:\d,?) Matches a Digit followed by a optional comma
    #   +        And at least one or more of the previous
    #   \d       Followed by a digit (To prevent it from matching `1234,.123`)
    #   \.?      Followed by a (optional) dot
    #            in case a fraction is mandatory, remove the `?` in the previous section.
    #   [0-9]*   Followed by any number of digits  -->  fraction? replace the `*` with a `+`
    # )/
    

提交回复
热议问题