PHP and preg_match Regex to pull number with decim

2020-02-13 05:16发布

问题:

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];  }

回答1:

Try this regex:

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

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

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

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


回答2:

Try this:

if (preg_match('/Weight: (\d+(\.\d+)?)/', $desc, $matches)) {
    echo $matches[1];
}


回答3:

preg_match('<li>Weight: (\d+)\.?(\d+)?.+</li>', // ...

Should to the trick



回答4:

if you JUST want to match a number integer OR decimal

 if (preg_match('/^(\d+(\.\d+)?)$/',$num)) echo "$num is integer or decimal";