PHP和preg_match正则表达式从字符串中提取带小数的数字 [英] PHP and preg_match Regex to pull number with decimal out of string

查看:922
本文介绍了PHP和preg_match正则表达式从字符串中提取带小数的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些基本的东西,试图使用regex和php从字符串中拉出 14.5 ,但我似乎语法不正确.另外,该数字是动态的,不一定总是十进制,但是这里的目标是尝试在单词Weight:</li>之间拉一个数字:

Pretty basic stuff here, trying to pull the number 14.5 out of this string using regex and php but I can't seem to get syntax correct. Also, the number is dynamic and may not always be a decimal but the goal here is to try and pull a number between the word Weight: and </li>:

  <ul>
    <li>Manufacturer: something</li>
    <li>Model: 1216D101</li>
    <li>Condition: New</li>
    <li>Dimensions: 12" x 16"</li>
    <li>Sold by the Dozen</li>
    <li>Weight: 14.5 Lbs.</li>
  </ul>

这是我到目前为止尝试过的方法,但仍存在不足:

This is what I have so far and have tried variations but keep falling short:

if (preg_match("/\Weight:\(\d+)\.(\d*?)\<\/li>/", $desc, $WEIGHT) == true)
    {  echo $WEIGHT[0];  }

推荐答案

尝试此正则表达式:

/Weight: ((?:\d+)(?:\.\d*)?)/

匹配的号码将在$WEIGHT[1]中提供.

The matched number will be available in $WEIGHT[1].

如果您不想以123.之类的数字捕获.:

If you don't want to capture the . in numbers like 123.:

/Weight: ((?:\d+)(?:\.\d+)?)/

这篇关于PHP和preg_match正则表达式从字符串中提取带小数的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆