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

前端 未结 7 582
一向
一向 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条回答
  • If you dont want to use regular expressions use filter_var:

    $str = "CASH55.35inMyPocket";
    var_dump( (float) filter_var( $str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) ); // float(55.35) 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 21:25
    function extract_numbers($string)
    {
    preg_match_all('/([\d]+)/', $string, $match);
    return $match[0];
    }
    
    0 讨论(0)
  • 2021-01-11 21:29

    You can try a little Function to extract that value for you before using either floatval or (float).

    Something like:

    function myFloats($str) {
    
      if(preg_match("#([0-9\.]+)#", $str, $match)) { // search for number that may contain '.'
        return floatval($match[0]);
      } else {
        return floatval($str); // take some last chances with floatval
      }
    }
    

    then test:

    echo myFloats("CASH55.35inMyPocket");
    
    0 讨论(0)
  • 2021-01-11 21:30

    Use a regex:

    preg_match('/([0-9]+\.[0-9]+)/', 'CASH55.35inMyPocket', $matches);
    $number = (float) $matches[1]; // 55.35
    
    0 讨论(0)
  • 2021-01-11 21:36

    I think a preg_replace could be helpfull here (untested):

    $float = preg_replace('/[^0-9\.]/', "", "CASH55.35inMyPocket"); // only show the numbers and dots
    

    You could extend the preg a little more to only get [number].[number], but in this case I think it will work.

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