2 回答

TA贡献1780条经验 获得超1个赞
解决此问题的一种方法是将成分列表拆分为逗号,然后过滤掉以开头的值,no然后再次内爆列表。这样做的好处是不会在输出中留下悬挂的逗号:
function filter_ingredients($elements) {
return implode(', ', array_filter(preg_split('/,\s*/', $elements), function ($v) {
return !preg_match('/^no\b/', $v);
}));
}
例如:
echo filter_ingredients("cheese, no tomato, no onion, mayo, no lettuce") . "\n";
echo filter_ingredients("no cheese, tomato, no onion, no mayo, lettuce") . "\n";
echo filter_ingredients("no cheese, no tomato, onion, no mayo, no lettuce") . "\n";
输出:
cheese, mayo
tomato, lettuce
onion
请注意,此代码假定您的成分中没有逗号。

TA贡献1842条经验 获得超21个赞
正则表达式可能不是防弹的,但这应该有效:
$pattern = '/,?\s*no \w+/';
$elements = "cheese, no tomato, no onion, mayo, no lettuce";
$str = preg_replace($pattern, '', $elements);
echo $str;
// echos "cheese, mayo"
不是“防弹”,我的意思是,例如,如果逗号之间的值中有逗号,那会导致问题等。
- 2 回答
- 0 关注
- 210 浏览
添加回答
举报