从逗号分隔的字符串中删除一个项目 [英] Remove an item from a comma-separated string

查看:148
本文介绍了从逗号分隔的字符串中删除一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串:

cat,mouse,dog,horse

是否存在可以按以下方式工作的正则表达式或函数?

Is there a regex or a function that will work as follows?

    1)"cat"       return string ->"mouse,dog,horse"
    2)"mouse"     return string ->"cat,dog,horse"
    3)"dog"       return string ->"cat,mouse,horse"
    4)"horse"     return string ->"cat,mouse,dog"

我需要从字符串中删除所选项目,然后返回字符串的其余部分.

I need to eliminate the selected item from the string and return the remaining parts of the string.

推荐答案

您的意思是删除某个元素的函数?试试这个:

You mean a function that removes a certain element? Try this:

function removeFromString($str, $item) {
    $parts = explode(',', $str);

    while(($i = array_search($item, $parts)) !== false) {
        unset($parts[$i]);
    }

    return implode(',', $parts);
}

演示

这篇关于从逗号分隔的字符串中删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆