我想用preg_replace替换括号或方括号内的所有逗号。
我可以使用下面的代码替换括号内的所有逗号:
$clean_ingredients = preg_replace('/(\([^)]*),([^)]*\))/', '$1! $2', $ingredients );
这导致括号内的逗号被替换,但我不知道如何检查方括号内的逗号。
我想达到的是:
$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).
有没有正则表达式Maven知道什么可以实现我所追求的?
2条答案
按热度按时间8zzbczxx1#
你可以用
参见PHP demo和regex demo。
\([^()]*\)|\[[^][]*]
正则表达式匹配\([^()]*\)
- a(
char +零个或多个除(
和)
以外的字符+ a)
char|
-或\[[^][]*]
- a[
char +零个或多个除[
和]
+ a]
char之外的char。preg_replace_callback
中的函数将所有逗号替换为!
+空格。cig3rfwq2#