phpregex

regex - what is the pattern for floating point digit next to unit


basically I want to match a simple thing in a str but only want to return the first part of this match. This is what I want to look in.

Jo 4.5 Oz cold and flu stuff to drink.

and what I want to do is return the 4.5 but only when the match is followed with a variation of the once unit.

Here is my guess

/([0-9]*\.?[0-9])(?:[\s+][o(?<=\.)z(?<=\.)|ounce]?=\s)/i

on matching:

4.5oz
4.5 oz
4.5 o.z.
4.5 oz.
4.5         oz.
4.5ounce
4.5Ounce
4.5 Oz.

but I get when I run it as of yet.

$matches = null;
$returnValue = preg_match('/([0-9]*\.?[0-9])(?:[\s+][o(?<=\.)z(?<=\.)|ounce]?=\s)/i', 'Jo 4.5 Oz cold and flu stuff to drink.', $matches);

Any help would be great. Thank you Cheers -Jeremy


Solution

  • Then you need a less complex pattern like:

    preg_match('/
          (\d+(\.\d+)?)              # float
          \s*                        # optional space
          ( ounce | o\.? z\.? )      # "ounce" or "o.z." or "oz"
       /ix',                         # make it case insensitive
       $string, $matches);
    

    Then either look at result $matches[1] or make the remainder an assertion with by enclosing it in (?=...) or so.