In Php, how to get float value from a mixed string?

前端 未结 7 628
一向
一向 2021-01-11 20:38

I got a string like:

$str = \"CASH55.35inMyPocket\";

I want to get 55.35 only.

I tried:

$str = flo         


        
7条回答
  •  温柔的废话
    2021-01-11 21:21

    What you have cannot be casted to a float, because it doesn't look like a float from PHP's perspective. It is possible to grab the value using regex though.

    If you are not sure whether there will always be a decimal. And you are trying to get the number regardless of position in the text (as per your question). You could use:

    ^.*?([\d]+(?:\.[\d]+)?).*?$
    

    Which gets the numeric values from the following strings:

    CASH55.35inMyPocket
    CASH55inMyPocket
    55.35inMyPocket
    55inMyPocket
    inMyPocket55.35
    inMyPocket55
    

    Explanation: http://regex101.com/r/tM8eM0
    Demo: http://rubular.com/r/Gw5HTzsejj
    PHP demo: https://eval.in/165521

    Basically it looks for numbers in the string. And optionally it also check for decimals after that.

提交回复
热议问题