2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
解決此問題的一種方法是將成分列表拆分為逗號(hào),然后過濾掉以開頭的值,no然后再次內(nèi)爆列表。這樣做的好處是不會(huì)在輸出中留下懸掛的逗號(hào):
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
請(qǐng)注意,此代碼假定您的成分中沒有逗號(hào)。

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
正則表達(dá)式可能不是防彈的,但這應(yīng)該有效:
$pattern = '/,?\s*no \w+/';
$elements = "cheese, no tomato, no onion, mayo, no lettuce";
$str = preg_replace($pattern, '', $elements);
echo $str;
// echos "cheese, mayo"
不是“防彈”,我的意思是,例如,如果逗號(hào)之間的值中有逗號(hào),那會(huì)導(dǎo)致問題等。
- 2 回答
- 0 關(guān)注
- 237 瀏覽
添加回答
舉報(bào)