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条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭