skip to Main Content

I’m looking to replace all commas that exist within a bracket or square bracket using preg_replace.

I am able to replace all commas inside brackets using the below:

$clean_ingredients = preg_replace('/(([^)]*),([^)]*))/', '$1! $2', $ingredients );

This results with commas inside brackets being replaced but I can’t work out how to also check for commas inside square brackets.

What I would like to achieve is:

$ingredients = "Skim Milk Powder, Condensed Milk, Coconut Cream, Strawberry Jam [Cane Sugar, Strawberries (40%), Gelling Agent (Fruit Pectin), Acidity Regulator (330)], Hazelnuts, Barley Malt Extract, Emulsifier (Soya Lecithin), Peppermint [Vegetable Oil, Peppermint Oil, Antioxidant (Mixed Tocopherols Concentrate)], Salt, Citric Acid, Flavouring (Vanillin), Vanilla, Colouring (E102, E133, E129, E132, E171, E122, E124, E110, E172, E153).";

$clean_ingredients = preg_replace('????', '$1! $2', $ingredients );

echo $clean_ingredients; 

// Output: Skim Milk Powder, Condensed Milk, Coconut Cream, Strawberry Jam [Cane Sugar! Strawberries (40%)! Gelling Agent (Fruit Pectin)! Acidity Regulator (330)], Hazelnuts, Barley Malt Extract, Emulsifier (Soya Lecithin), Peppermint [Vegetable Oil! Peppermint Oil! Antioxidant (Mixed Tocopherols Concentrate)], Salt, Citric Acid, Flavouring (Vanillin), Vanilla, Colouring (E102! E133! E129! E132! E171! E122! E124! E110! E172! E153).

Is there any regex experts out there that know what could achieve what I’m after?

2

Answers


  1. You can use

    <?php
    
    $ingredients = "aaa (1,2,3) bbb [4,5,6,7]";
    $clean_ingredients = preg_replace_callback('/([^()]*)|[[^][]*]/', function($m) {return str_replace(',', '! ', $m[0]);}, $ingredients );
    echo $clean_ingredients;
    // => aaa (1! 2! 3) bbb [4! 5! 6! 7]
    

    See the PHP demo and the regex demo.

    The ([^()]*)|[[^][]*] regex matches

    • ([^()]*) – a ( char + zero or more chars other than ( and ) + a ) char
    • | – or
    • [[^][]*] – a [ char + zero or more chars other than [ and ] + a ] char.

    The function inside preg_replace_callback replaces all commas with ! + space.

    Login or Signup to reply.
  2. $ingredients = "Skim Milk Powder, Condensed Milk, Coconut Cream, Strawberry Jam [Cane Sugar, Strawberries (40%), Gelling Agent (Fruit Pectin), Acidity Regulator (330)], Hazelnuts, Barley Malt Extract, Emulsifier (Soya Lecithin), Peppermint [Vegetable Oil, Peppermint Oil, Antioxidant (Mixed Tocopherols Concentrate)], Salt, Citric Acid, Flavouring (Vanillin), Vanilla, Colouring (E102, E133, E129, E132, E171, E122, E124, E110, E172, E153).";
    
    echo preg_replace_callback('~[[^]]+|([^)]+~', fn($m) => strtr($m[0], ',', '!'), $ingredients);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search