dsa99349 2016-03-17 09:56
浏览 446
已采纳

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 2016-03-17 10:08
    关注

    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"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?