You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP preg_replace替换括号及方括号内的所有逗号?

解决方案

要同时替换圆括号()和方括号[]内的所有逗号,需支持嵌套括号场景,推荐用preg_replace_callback实现,比单纯preg_replace更灵活且覆盖所有情况:

$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_callback(
    '/(\[(?:[^[\]]|(?R))*\]|\((?:[^()]|(?R))*\))/',
    function($match) {
        return str_replace(',', '! ', $match[0]);
    },
    $ingredients
);

echo $clean_ingredients;

正则说明

  • \[(?:[^[\]]|(?R))*\]:匹配平衡的方括号结构,(?R)递归匹配整个正则,可处理嵌套的括号
  • \((?:[^()]|(?R))*\):匹配平衡的圆括号结构,同样支持嵌套
  • 回调函数将匹配到的括号内所有逗号替换为!

如果必须用纯preg_replace(需循环多次替换直到无匹配),可使用以下代码,但对深层嵌套场景支持有限:

do {
    $clean_ingredients = preg_replace('/((?:\[(?:[^[\]]*|\((?:[^()]*)\))*|\((?:[^()]*)\))*),/', '$1! ', $ingredients, -1, $count);
} while ($count > 0);

内容的提问来源于stack exchange,提问作者Jason Stockton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:17:37