Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

print values between words PHP

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 whitespace
  • k?cal match cal or kcal
  • \b word boundary
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading