为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
小唯快跑啊 2022-10-14 10:41:41
如何从 $elements 中删除带有“no”的任何内容及其各自的逗号,留下其余部分?$elements = "cheese, no tomato, no onion, mayo, no lettuce";
查看完整描述

2 回答

?
慕神8447489

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

3v4l.org 上的演示

请注意,此代码假定您的成分中没有逗号。


查看完整回答
反对 回复 2022-10-14
?
茅侃侃

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"

不是“防弹”,我的意思是,例如,如果逗号之间的值中有逗号,那会导致问题等。


查看完整回答
反对 回复 2022-10-14
  • 2 回答
  • 0 关注
  • 182 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信