PHP preg_replace括号和方括号内的所有逗号

rslzwgfq  于 2023-05-16  发布在  PHP
关注(0)|答案(2)|浏览(104)

我想用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知道什么可以实现我所追求的?

8zzbczxx

8zzbczxx1#

你可以用

<?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]

参见PHP demoregex demo
\([^()]*\)|\[[^][]*]正则表达式匹配

  • \([^()]*\)- a ( char +零个或多个除()以外的字符+ a ) char
  • |-或
  • \[[^][]*]- a [ char +零个或多个除[] + a ] char之外的char。

preg_replace_callback中的函数将所有逗号替换为!+空格。

cig3rfwq

cig3rfwq2#

$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);

相关问题