Search code examples
phpstringsubstringstrposdisplay-cutouts

Strip out a substring beginning with a specific word and ending with "."


From the middle of a text I need to cut out a sentence or better the information about the ingredients of a product. The logic behind is always the same. Starting with "Ingredients" ending with a dot "."

For example (this is my $prodDesc):

Coca Cola is the most famous soft drink in America.
Ingredients: Carbon water, Sugar (sucrose or high-fructose corn syrup (HFCS) depending on country of origin), Caramel colour (E150d), Phosphoric Acid, Caffeine (34 mg/12 fl oz), natural Flavours. Nutrition Facts: 1 Serving Per Container - Serving Size: 1 Can. Total Fat 0g Sodium 45mg Total Carbohydrate 39g Total Sugars (Includes 39g Added Sugars) Cholesterol 0mg Protein 0g Vitamin D 0g Calcium 0g Iron 0g Potassium 0g

I tried so far with strpros but the fact it is in the middle of the text I get everything from "Ingredients" on until the end.

I need only this as output:

$prodIngredientsData = "Ingredients: Carbon water, Sugar (sucrose or high-fructose corn syrup (HFCS) depending on country of origin), Caramel colour (E150d), Phosphoric Acid, Caffeine (34 mg/12 fl oz), natural Flavours."

Given that $prodDesc is the description above, my try was:

$searchstring = $prodDesc;
$prodIngredientsData = false;
if (strpos($searchstring, "Ingredients") !== false)
{
    $sd_array = explode("Ingredients", $searchstring);
    $sd = end($sd_array);
    $prodIngredientsData = "Ingredients " . $sd;
}
else {
    $prodIngredientsData = false;
}

But as mentioned, I get everything on from "Ingredients" until the end of the description. But it should stop at the first full stop in the example at "Ingredients... ...natural Flavours."


Solution

  • try with preg_match:

    $prodIngredientsData = "Ingredients: Carbon water, Sugar (sucrose or high-fructose corn syrup (HFCS) depending on country of origin), Caramel colour (E150d), Phosphoric Acid, Caffeine (34 mg/12 fl oz), natural Flavours."
    preg_match('/(Ingredients:([^.]+))/', $prodIngredientsData, $matches);
    
    echo $matches[0];
    

    Output:

    Ingredients: Carbon water, Sugar (sucrose or high-fructose corn syrup (HFCS) depending on country of origin), Caramel colour (E150d), Phosphoric Acid, Caffeine (34 mg/12 fl oz), natural Flavou rs