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
You can use
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.