doulian4762 2014-04-19 04:58
浏览 27
已采纳

preg_replace正在取代一切

I want to replace certain html tags with null string and want to retrieve text only. Below is the example that I want.

preg_match_all("/<span id=\"priceblock_ourprice\" class=\"a-size-medium a-color-price\">(.*)<\/span>/U", $content, $matches);

The above line retrieves something like this.

<span id="priceblock_ourprice" class="a-size-medium a-color-price">50</span>

Now, I want to retrieve the integer value only (i.e 50). I tried the following statement to remove the HTML tags.

    foreach($matches[0] as $key=>$val) {
        $price = preg_replace( '/<(.*)>/', '', $val);
    }

But the problem is, it replaces everything, and a null string is returned. It should return 50, no the null. The output file $price variable should be like:

$price = 50
  • 写回答

2条回答 默认 最新

  • dqqlziv195281 2014-04-19 05:00
    关注

    Try adding a question mark to your regular expression

    foreach($matches[0] as $key=>$val) {
      $price = preg_replace( '/<(.*?)>/', '', $val);
    }
    

    This will have the effect of finding the first > instead of the last one. Regular expressions are greedy and will find everything it can.

    Also, keep in mind that the way you are doing this will replace $price with each loop. I am assuming you're doing something with $price before the next loop occurs, but if not, you should store the price in an array.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分