如何从逗号分隔列表中删除以“no”开头的短语及其各自的逗号,留下其余的?

如何从 $elements 中删除带有“no”的任何内容及其各自的逗号,留下其余部分?

$elements = "cheese, no tomato, no onion, mayo, no lettuce";


小唯快跑啊
浏览 211回答 2
2回答

慕神8447489

解决此问题的一种方法是将成分列表拆分为逗号,然后过滤掉以开头的值,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, mayotomato, lettuceonion3v4l.org 上的演示请注意,此代码假定您的成分中没有逗号。

茅侃侃

正则表达式可能不是防弹的,但这应该有效:$pattern = '/,?\s*no \w+/';$elements = "cheese, no tomato, no onion, mayo, no lettuce";$str = preg_replace($pattern, '', $elements);echo $str;// echos "cheese, mayo"不是“防弹”,我的意思是,例如,如果逗号之间的值中有逗号,那会导致问题等。
打开App,查看更多内容
随时随地看视频慕课网APP