Made in a facility that uses allergens (GLUTEN, SOY, CELERY, NUTS). Energy value: 971kJ /234kcal. 100g of product contains: fat 18.1g, including saturated fatty acids 6g.
I need to display the calorie values.
There may be a space before 234kcal
, or it may be, as it is now, merged with /
Maybe everything is merged at once 971kJ/234kcal
, or maybe there are gaps
971kJ / 234kcal
I need to get out anyway only Kcal value.
$info_in_text = "Made in a facility that uses allergens (GLUTEN, SOY, CELERY, NUTS). Energy value: 971kJ /234kcal. 100g of product contains: fat 18.1g, including saturated fatty acids 6g.";
$pieces = explode(" ", $info_in_text);
foreach( $pieces as $key => $value )
{
if($pieces[$key] == 'value:' )
{
echo $pieces[$key 2];
}
}
I tried that, but it doesn't work correctly. It is necessary that in any case it displays only calorie values (kcal ). in this case, displays if there are no spaces or not everything is merged.
CodePudding user response:
Using preg_match_all()
with a regular expression we can try:
$input = "Made in a facility that uses allergens (GLUTEN, SOY, CELERY, NUTS). Energy value: 971kJ /234kcal. 100g of product contains: fat 18.1g, including saturated fatty acids 6g.";
preg_match_all("/\d (?:\.\d )?\s*k?cal\b/", $input, $result);
print_r($result[0][0]); // 234kcal
The regex pattern used here says to match:
\d (?:\.\d )?
an integer or decimal number\s*
optional whitespacek?cal
matchcal
orkcal
\b
word boundary