dsa99349
dsa99349
2016-03-17 09:56

PHP如何获取字符串中的第二个数字


I would like to get the second number present in a string. Maybe you have better ideas than mine.

From this example:

1 PLN = 0.07 Gold

I would like to get only "0.07" from that string. I obtain it from web scraping so it returns me as a string.

The problem that I have is the following. The "second number in string" might be with ".", without it, might be composed by only one number ex. "1", or by two "12", might have decimals ex. "1.2", even position may change, because for some currency I will have "1 PLN", "1 USD" for others I will have "1 TW".

So I can't work on position, I can't extract only numbers (I have the "1" at the beginning of the string), I can't extract only INT cause I could have also decimals...

So the only constant of that string - I think (but if you have better ideas pls suggest me) - is that I need the second number I find in the string.

How could I get it? Sorry If I wasn't enough clear.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dounao5856 dounao5856 5年前

    Try this:

    <?php
    $string = '1 PLN = 0.07 Gold';
    $pattern = '/\d+\.\d+/';
    
    $matches = array();
    $r = preg_match($pattern, $string, $matches);
    
    var_dump($matches); //$matches is array with results
    

    Output:

    array(1) {
      [0]=>
      string(4) "0.07"
    }
    
    点赞 评论 复制链接分享
  • dougouqin0763 dougouqin0763 5年前

    You can use a simple regex patter to isolate all numbers, including decimals if any after the equals sign.

    The below works if the string will have the same structure, meaning an = a space and then the number that you are after.

    = - matches the equals sign
    \s - matches the space character immediately after
    (\d*\.?\d*) - matches any number of digits followed by an optional period . and then any number of digits

    $str = '1 PLN = 0.07 Gold';
    
    preg_match('#=\s(\d*\.?\d*)#',$str,$matches);
    
    print $matches[1];
    

    Will output

    0.07
    

    This works regardless of what you have before the = sign.

    点赞 评论 复制链接分享
  • dsfphczao23473056 dsfphczao23473056 5年前

    If its always in this format 1 PLN = 0.07 Gold You can just

    $array = explode(" ", $string) with a Space and then get the required number with

    $number = $array[3]
    

    Try it out, let me know if it works

    点赞 评论 复制链接分享

为你推荐