dqalnwuci494308 2016-03-08 15:54
浏览 15
已采纳

删除所有文本2位小数后放置PHP

I'm trying to scrape a products price from a page, however unfortunately it's not in a nice clean div so I'm having to clear all the other junk.

Note: I have looked at several examples however they all assume you only have nice organised numbers in your variable, not raw HTML stuffed on the end.

An example of the string my variable may hold:

$2.87 <span>10% Off Sale</span>

I've played about with substr and sttrpos, read the manual and still can't figure it out on my own.

I want to just cut the string two digits after the first decimal place is found... No doubt it's extremely simple when you know how!

What I want to end up with:

$2.87

An example of the mess I've got myself into trying:

$whatIWant = substr($data, strrpos($data, ".") + 2);

Thanks in advance,

  • 写回答

3条回答 默认 最新

  • dongshi2458 2016-03-08 16:03
    关注

    Try this solution:

    <?php
    
    $string = "$2.87 <span>10% Off Sale</span>";
    
    $matches = array();
    preg_match('/(\$\d+\.\d{2})/', $string, $matches);
    
    var_dump($matches);
    

    Output:

    array(2) {
      [0]=>
      string(5) "$2.87"
      [1]=>
      string(5) "$2.87"
    }
    

    For more info (why result is array etc.) you should check PHP manual on preg_match() function: link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算