Reputation: 1476
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
Upvotes: 2
Views: 521
Reputation: 1750
I think it's probably a little more simple than what you're trying there. Give this expression a try:
\s\d+.\d+\s*(oz|ounce|o\.z\.|oz\.)
Or with full php:
$test_string = 'Jo 4.5 Oz cold and flu stuff to drink.';
$returnValue = preg_match('/\s\d+.\d+\s*(oz|ounce|o\.z\.|oz\.)/i', $test_string, $matches);
EDIT
If you want to check if they use a .
or a ,
you could use:
\d+(\.|,)\d+\s*(ounce|o\.?z\.?)
or
$returnValue = preg_match('/\d+(\.|,)\d+\s*(ounce|o\.?z\.?)/ix', $test_string, $matches);
EDIT 2
If you want named patterns try this:
$returnValue = preg_match('/(?P<amount>\d+(\.|,)\d+)\s*(?P<unit>(ounce|o\.?z\.?))/ix', $test_string, $matches);
print_r($matches);
Output:
Array
(
[0] => 4.5 Oz
[amount] => 4.5
[1] => 4.5
[2] => .
[unit] => Oz
[3] => Oz
[4] => Oz
)
Upvotes: 1
Reputation: 145482
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.
Upvotes: 2